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. 7. Reverse Integer Add to List★

    题目内容: Reverse digits of an integer. Example1: x = 123, return 321Example2: x = -123, return -321 题目分 ...

  2. Idea中:No converter found for return value of type: class java.util.ArrayList:Json格式转换问题

    1.在搞SSM框架的时候,前端发送请求后,显示如下错误. @ResponseBody注解进行返回List<对象>的json数据时出现 nested exception is java.la ...

  3. 记一次 SSM 分页

    1.实体层(entity,pojo,domain) package com.entity; import java.io.Serializable; private int totalCount; / ...

  4. 凯撒密码移位python

    #!/usr/bin/python'''凯撒密码'''a="gmbhqwertghjkcvbzn"s=[""]*len(a)for j in range(26) ...

  5. CISCO 关闭4786端口解决方法

    先确认交换机是否支持smart install服务 检查命令如下: switch#show vstack config | inc Role Role:Client (SmartInstall ena ...

  6. C++ Coroutine简明教程

    在C++里,一个函数如果其函数体实现中包含co_await.co_yield.co_return中任何一个关键字,那么这个函数就是一个coroutine.其中: co_await:挂起当前的corou ...

  7. python基础 字典练习

    练习1:info = [ {'wangming': { 'money':1111, 'car':['bmo','bsj'], 'info':{ 'phone':1511111, 'age':18} } ...

  8. myeclipse 与 mysql 的连接

    在小学期的学习中,我了解了myeclipse的开发环境,与mysql连接,可对数据库进行增.删.改.查等操作,以下是在myeclipse中连接数据库的代码. package cn.neusoft.my ...

  9. java常用类( 下 )

  10. TCPIP学习笔记

    TCP的连接 状态变化 各个状态的意义如下: LISTEN - 侦听来自远方TCP端口的连接请求: SYN-SENT -在发送连接请求后等待匹配的连接请求: SYN-RECEIVED - 在收到和发送 ...