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的更多相关文章

  1. 038. asp.netWeb用户控件之六实现日期选择的用户控件

    web用户控件的ascx代码: <%@ Control Language="C#" AutoEventWireup="true" CodeFile=&qu ...

  2. 035. asp.netWeb用户控件之四通过用户控件实现投票和结果分析

    用户控件Vote.ascx代码 <%@ Control Language="C#" AutoEventWireup="true" CodeFile=&qu ...

  3. 《ASP.NET1200例》实现投票的用户控件

    用户控件ascx <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="24 ...

  4. C# 自定义控件VS用户控件

    1 自定义控件与用户控件区别 WinForm中, 用户控件(User Control):继承自 UserControl,主要用于开发 Container 控件,Container控件可以添加其他Con ...

  5. .net 用户控件ascx.cs注册js脚本代码无效果

    在.net web项目中碰到一个比较奇怪的问题,网上没找到解决方案,先自己mark一下 问题描述: 添加一个用户控件ascx,在后端.cs添加js注册脚本,执行后没有弹出框 注册脚本为: this.P ...

  6. winform 用户控件、 动态创建添加控件、timer控件、控件联动

    用户控件: 相当于自定义的一个panel 里面可以放各种其他控件,并可以在后台一下调用整个此自定义控件. 使用方法:在项目上右键.添加.用户控件,之后用户控件的编辑与普通容器控件类似.如果要在后台往窗 ...

  7. C#窗体程序【用户控件-窗体】委托事件

    这里的自定义控件是由普通控件组合而成的.希望事件响应代码推迟到使用自定义控件的窗体里写.步骤一:新建一个用户控件,放两个按钮,Tag分别是btn1,btn2.这两个按钮的共用单击事件处理代码如下: u ...

  8. WinForm用户控件、动态创建添加控件、timer控件--2016年12月12日

    好文要顶 关注我 收藏该文 徐淳 关注 - 1 粉丝 - 3       0 0     用户控件: 通过布局将多个控件整合为一个控件,根据自己的需要进行修改,可对用户控件内的所有控件及控件属性进行修 ...

  9. wpf的UserControl用户控件怎么添加到Window窗体中

    转载自 http://www.cnblogs.com/shuang121/archive/2013/01/09/2853591.html 我们来新建一个用户控件UserControl1.xaml &l ...

随机推荐

  1. Linux SSH登录服务器报ECDSA host key "ip地址" for has changed and you have requested strict checking错误

    错误:ECDSA host key "ip地址" for  has changed and you have requested strict checking. 解决方案:在终端 ...

  2. DNS区域传送、子域授权

    前言 DNS服务器搭建参考上一篇: DNS主从复制,就是将主DNS服务器的解析库复制传送至从DNS服务器,进而从服务器就可以进行正向.反向解析了.从服务器向主服务器更新查询数据,保证数据一致性,此为区 ...

  3. vue 路由(1)

    路由的使用  (5步) 1.首先安装路由  npm install  vue-router2.引入 vue-router import VueRouter from 'vue-router' 3.使用 ...

  4. sciense

    I hate the word "networking." It must be one of the most overused words in the English lan ...

  5. 13. Roman to Integer ★

    题目内容: Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range fr ...

  6. 一个简单的Quartz定时任务

    package com.shuadan.quartz; import org.springframework.scheduling.annotation.Scheduled; import org.s ...

  7. open还是codecs.open区别

    >>> fr = open('test.txt','a')>>> line1 = "我是一道光">>> fr.write(li ...

  8. DAY5:字典

    无序性: # -*- coding:utf-8 -*- # Author: TanJincheng room = { "s2": "han meimei", & ...

  9. 搭建NTP服务集群、高可用

    1.原理 Keepalived 的作用是检测后端服务器的状态,如果有一台服务器死机,或工作出现故障,Keepalived 将检测到,并将有故障的服务器从系统中剔除.当服务器工作正常后 Keepaliv ...

  10. 用 Cobertura 测量测试覆盖率

      尽管测试先行编程(test-first programming)和单元测试已不能算是新概念,但测试驱动的开发仍然是过去 10 年中最重要的编程创新.最好的一些编程人员在过去半个世纪中一直在使用这些 ...