用户控件 RadioButtonList
public static MvcHtmlString RadioButtonList(this HtmlHelper htmlHelper, string name, string codeCategory, RepeatDirection repeatDirection = RepeatDirection.Horizontal)
{
var codes = CodeManager.GetCodes(codeCategory);
return ListControlUtil.GenerateHtml(name, codes, repeatDirection, "radio", null);
}
public static MvcHtmlString RadioButtonListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, Collection<CodeDescription> codeCategory,CodeDescription selectCodeCategory, RepeatDirection repeatDirection = RepeatDirection.Horizontal)
{
ModelMetadata metadata = ModelMetadata.FromLambdaExpression<TModel, TProperty>(expression, htmlHelper.ViewData);
string name = ExpressionHelper.GetExpressionText(expression);
string fullHtmlFieldName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);
return ListControlUtil.GenerateHtml(fullHtmlFieldName, codeCategory, selectCodeCategory, repeatDirection, "radio", metadata.Model);
}
public static MvcHtmlString RadioButtonListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, Collection<CodeDescription> codeCategory, RepeatDirection repeatDirection = RepeatDirection.Horizontal)
{
ModelMetadata metadata = ModelMetadata.FromLambdaExpression<TModel, TProperty>(expression, htmlHelper.ViewData);
string name = ExpressionHelper.GetExpressionText(expression);
string fullHtmlFieldName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);
return ListControlUtil.GenerateHtml(fullHtmlFieldName, codeCategory, repeatDirection, "radio", metadata.Model);
} public static MvcHtmlString RadioButtonListForOne<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, string optionLabel, IDictionary<string, object> htmlAttributes)
{
if (expression == null)
{
throw new ArgumentNullException("expression");
}
string name = ExpressionHelper.GetExpressionText(expression); string fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);
if (String.IsNullOrEmpty(fullName))
{
throw new ArgumentException("name");
} bool usedViewData = false; // If we got a null selectList, try to use ViewData to get the list of items.
if (selectList == null)
{
selectList = htmlHelper.GetSelectData(fullName);
usedViewData = true;
} object defaultValue = htmlHelper.GetModelStateValue(fullName, typeof(string)); // If we haven't already used ViewData to get the entire list of items then we need to
// use the ViewData-supplied value before using the parameter-supplied value.
if (!usedViewData)
{
if (defaultValue == null)
{
defaultValue = htmlHelper.ViewData.Eval(fullName);
}
}
if (defaultValue != null)
{
IEnumerable defaultValues = new[] { defaultValue };
IEnumerable<string> values = from object value in defaultValues select Convert.ToString(value, CultureInfo.CurrentCulture);
HashSet<string> selectedValues = new HashSet<string>(values, StringComparer.OrdinalIgnoreCase);
List<SelectListItem> newSelectList = new List<SelectListItem>(); foreach (SelectListItem item in selectList)
{
item.Selected = (item.Value != null) ? selectedValues.Contains(item.Value) : selectedValues.Contains(item.Text);
newSelectList.Add(item);
}
selectList = newSelectList;
} #region TagBuilder table = new TagBuilder("table");
int i = ; foreach (SelectListItem item in selectList)
{
//
TagBuilder tr = new TagBuilder("tr");
i++;
string id = string.Format("{0}_{1}", name, i);
TagBuilder td = new TagBuilder("td");
td.InnerHtml = GenerateRadioHtml(name, id, item.Text, item.Value, item.Selected, htmlAttributes);
tr.InnerHtml = td.ToString();
table.InnerHtml += tr.ToString();
} #endregion return new MvcHtmlString(table.ToString());
} private static IEnumerable<SelectListItem> GetSelectData(this HtmlHelper htmlHelper, string name)
{
object o = null;
if (htmlHelper.ViewData != null)
{
o = htmlHelper.ViewData.Eval(name);
}
if (o == null)
{
throw new InvalidOperationException(
"IEnumerable<SelectListItem>");
}
IEnumerable<SelectListItem> selectList = o as IEnumerable<SelectListItem>;
if (selectList == null)
{
throw new InvalidOperationException(
"IEnumerable<SelectListItem>");
}
return selectList;
}
private static object GetModelStateValue(this HtmlHelper htmlHelper, string key, Type destinationType)
{
ModelState modelState;
if (htmlHelper.ViewData.ModelState.TryGetValue(key, out modelState))
{
if (modelState.Value != null)
{
return modelState.Value.ConvertTo(destinationType, null /* culture */);
}
}
return null;
}
private static string GenerateRadioHtml(string name, string id, string labelText, string value, bool isChecked, IDictionary<string, object> htmlAttributes)
{
StringBuilder sb = new StringBuilder(); TagBuilder label = new TagBuilder("label");
label.MergeAttribute("for", id);
label.SetInnerText(labelText); TagBuilder input = new TagBuilder("input");
input.GenerateId(id);
input.MergeAttribute("name", name);
input.MergeAttribute("type", "radio");
input.MergeAttribute("value", value);
input.MergeAttributes(htmlAttributes);
if (isChecked)
{
input.MergeAttribute("checked", "checked");
}
sb.AppendLine(input.ToString());
sb.AppendLine(label.ToString());
return sb.ToString();
}
引用
public static class ListControlUtil
{
public static MvcHtmlString GenerateHtml(string name, Collection<CodeDescription> codes, RepeatDirection repeatDirection, string type, object stateValue)
{
TagBuilder table = new TagBuilder("table");
int i = ;
bool isCheckBox = type == "checkbox";
if (repeatDirection == RepeatDirection.Horizontal)
{
TagBuilder tr = new TagBuilder("tr");
if (codes == null) { return null; }
foreach (var code in codes)
{
i++;
string id = string.Format("{0}_{1}", name, i);
TagBuilder td = new TagBuilder("td"); bool isChecked = false;
if (isCheckBox)
{
IEnumerable<string> currentValues = stateValue as IEnumerable<string>;
isChecked = (null != currentValues && currentValues.Contains(code.Code));
}
else
{
string currentValue = stateValue.ToString();
isChecked = (null != currentValue && code.Code == currentValue);
} td.InnerHtml = GenerateRadioHtml(name, id, code.Description, code.Code, isChecked, type);
tr.InnerHtml += td.ToString();
}
table.InnerHtml = tr.ToString();
}
else
{
foreach (var code in codes)
{
TagBuilder tr = new TagBuilder("tr");
i++;
string id = string.Format("{0}_{1}", name, i);
TagBuilder td = new TagBuilder("td"); bool isChecked = false;
if (isCheckBox)
{
IEnumerable<string> currentValues = stateValue as IEnumerable<string>;
isChecked = (null != currentValues && currentValues.Contains(code.Code));
}
else
{
string currentValue = stateValue as string;
isChecked = (null != currentValue && code.Code == currentValue);
} td.InnerHtml = GenerateRadioHtml(name, id, code.Description, code.Code, isChecked, type);
tr.InnerHtml = td.ToString();
table.InnerHtml += tr.ToString();
}
}
return new MvcHtmlString(table.ToString());
}
public static MvcHtmlString GenerateHtml(string name, Collection<CodeDescription> codes, CodeDescription selectCodeCategory, RepeatDirection repeatDirection, string type, object stateValue)
{
TagBuilder table = new TagBuilder("table");
int i = ;
bool isCheckBox = type == "checkbox";
if (repeatDirection == RepeatDirection.Horizontal)
{
TagBuilder tr = new TagBuilder("tr");
foreach (var code in codes)
{
i++;
string id = string.Format("{0}_{1}", name, i);
TagBuilder td = new TagBuilder("td"); bool isChecked = false;
if (isCheckBox)
{
IEnumerable<string> currentValues = stateValue as IEnumerable<string>;
isChecked = (null != currentValues && currentValues.Contains(code.Code));
}
else
{
string currentValue = selectCodeCategory.Code;
isChecked = (null != currentValue && code.Code == currentValue);
} td.InnerHtml = GenerateRadioHtml(name, id, code.Description, code.Code, isChecked, type);
tr.InnerHtml += td.ToString();
}
table.InnerHtml = tr.ToString();
}
else
{
foreach (var code in codes)
{
TagBuilder tr = new TagBuilder("tr");
i++;
string id = string.Format("{0}_{1}", name, i);
TagBuilder td = new TagBuilder("td"); bool isChecked = false;
if (isCheckBox)
{
IEnumerable<string> currentValues = stateValue as IEnumerable<string>;
isChecked = (null != currentValues && currentValues.Contains(code.Code));
}
else
{
string currentValue = selectCodeCategory.Code;
isChecked = (null != currentValue && code.Code == currentValue);
} td.InnerHtml = GenerateRadioHtml(name, id, code.Description, code.Code, isChecked, type);
tr.InnerHtml = td.ToString();
table.InnerHtml += tr.ToString();
}
}
return new MvcHtmlString(table.ToString());
} private static string GenerateRadioHtml(string name, string id, string labelText, string value, bool isChecked, string type)
{
StringBuilder sb = new StringBuilder(); TagBuilder label = new TagBuilder("label");
label.MergeAttribute("for", id);
label.SetInnerText(labelText); TagBuilder input = new TagBuilder("input");
input.GenerateId(id);
input.MergeAttribute("name", name);
input.MergeAttribute("type", type);
input.MergeAttribute("value", value);
if (isChecked)
{
input.MergeAttribute("checked", "checked");
}
sb.AppendLine(input.ToString());
sb.AppendLine(label.ToString());
return sb.ToString();
}
}
控件所用自定义类CodeDescription
public class CodeDescription
{
public string Code { get; set; }
public string Description { get; set; }
public string Category { get; set; } public CodeDescription(string code, string description, string category)
{
this.Code = code;
this.Description = description;
this.Category = category;
}
}
使用方法初始化Controller
Collection<CodeDescription> listSex = new Collection<CodeDescription>();
listSex.Add(new CodeDescription( "", "男", "Sex" ));
listSex.Add(new CodeDescription("", "女", "Sex"));
ViewBag.SexItems = listSex;
model.SexItems = listSex;
model.SexSeltectItem = new CodeDescription("", "男", "Sex");
前端使用
@Html.RadioButtonListFor(c => c.Sex, Model.SexItems,Model.SexSeltectItem)@Html.ValidationMessageFor(model => model.Sex)
控制器获取
obj.Sex = model.Sex;
用户控件 RadioButtonList的更多相关文章
- 038. asp.netWeb用户控件之六实现日期选择的用户控件
web用户控件的ascx代码: <%@ Control Language="C#" AutoEventWireup="true" CodeFile=&qu ...
- 035. asp.netWeb用户控件之四通过用户控件实现投票和结果分析
用户控件Vote.ascx代码 <%@ Control Language="C#" AutoEventWireup="true" CodeFile=&qu ...
- 《ASP.NET1200例》实现投票的用户控件
用户控件ascx <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="24 ...
- C# 自定义控件VS用户控件
1 自定义控件与用户控件区别 WinForm中, 用户控件(User Control):继承自 UserControl,主要用于开发 Container 控件,Container控件可以添加其他Con ...
- .net 用户控件ascx.cs注册js脚本代码无效果
在.net web项目中碰到一个比较奇怪的问题,网上没找到解决方案,先自己mark一下 问题描述: 添加一个用户控件ascx,在后端.cs添加js注册脚本,执行后没有弹出框 注册脚本为: this.P ...
- winform 用户控件、 动态创建添加控件、timer控件、控件联动
用户控件: 相当于自定义的一个panel 里面可以放各种其他控件,并可以在后台一下调用整个此自定义控件. 使用方法:在项目上右键.添加.用户控件,之后用户控件的编辑与普通容器控件类似.如果要在后台往窗 ...
- C#窗体程序【用户控件-窗体】委托事件
这里的自定义控件是由普通控件组合而成的.希望事件响应代码推迟到使用自定义控件的窗体里写.步骤一:新建一个用户控件,放两个按钮,Tag分别是btn1,btn2.这两个按钮的共用单击事件处理代码如下: u ...
- WinForm用户控件、动态创建添加控件、timer控件--2016年12月12日
好文要顶 关注我 收藏该文 徐淳 关注 - 1 粉丝 - 3 0 0 用户控件: 通过布局将多个控件整合为一个控件,根据自己的需要进行修改,可对用户控件内的所有控件及控件属性进行修 ...
- wpf的UserControl用户控件怎么添加到Window窗体中
转载自 http://www.cnblogs.com/shuang121/archive/2013/01/09/2853591.html 我们来新建一个用户控件UserControl1.xaml &l ...
随机推荐
- 1.2 JAVA多线程实现
线程和进程 进程:是执行中一段程序, 进程是系统进行资源分配和调度的一个独立单位. 线程:比进程更小的能独立运行的基本单位,单个进程中执行中每个任务就是一个线程.线程是进程中执行运算的最小单位. Th ...
- jQuery获取name相同被选中的多选框的值
var name= ""; $("input:checkbox[name='AllElection']:checked").each(fu ...
- 最大流 USTC1280
挺有意思的一题,最小路径之后最大流 /************************************************************** 作者:陈新 邮箱:cx2pirate ...
- Create Maximum Number
Given two arrays of length m and n with digits 0-9 representing two numbers. Create the maximum numb ...
- Qunar入职前自学笔记
Q1. 什么是html,html发展历程 hyperText markup language 超文本标记语言 HTML是用于描述网页文档的标记语言.现在我们常常习惯于用数字来描述HTML的版本(如:H ...
- tensorFlow可以运行的代码
折腾了很久,终于运行成功. 才云科技的书不错,就是需要微调一二. 心得:1,记得activate tensorflow,然后再python 2,Python的代码格式很重要,不要错误. 3,还不清楚如 ...
- vue axios上传文件实例
<head> <title></title> <meta charset="UTF-8"> <meta name=" ...
- Vue源码之----为什么Vue中Array的pop,push等方法可以reactive,而Array[0]='a'这样的方法不会reactive?
这就要从reactive开始讲起了,粗略的说,js的操作能引起页面上显示的改变,是因为该操作引起了组件的重新渲染,渲染会生成新的虚拟节点,新节点和旧节点会对比,操作浏览器的node进行改变. vue实 ...
- 18-09-16如何从pychram的第三方包导入设计器
1 在pychrm 中的操作 2 找到pycharm 中找到对应的包 3 找到设计器中文件夹 后进行复制即可
- 利用div+css实现九宫格,然后用js实现点击每个格子可以随机更改格子(div)的背景颜色
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...