热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

ASP.NETMVC中使用“RadioButtonList”和“CheckBoxList”

一、有何特别之处?和我的很多文章一样,旨在提供一种大体的解决方案,本解决方案旨在解决如下一些问题:通过独立的组件对绑定到Li
一、有何特别之处?

和我的很多文章一样,旨在提供一种大体的解决方案,本解决方案旨在解决如下一些问题:

  • 通过独立的组件对绑定到ListControl(ASP.NET Web Form的说法)的列表进行单独管理;
  • 自动地调用上面这个组件获取列表信息进行相关Html的生成;
  • 支持ASP.NET MVC原生的Model Binding。
二、实例演示

下面是代表个人信息同时作为Model的Person类型,Gender、MaritalStatus 和Country分别代表性别、婚姻状况和国籍(这里支持多国籍)。

public class Person
{public string Name { get; set; }public string Gender { get; set; }[Display(Name = "Marital Status")]public string MaritalStatus { get; set; }public string[] Country { get; set; }
}

  

上述三个属性分别代表CodeManager这个独立组件维护的三个列表,CodeManager和代表列表选项的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;}}public static class CodeManager{private static CodeDescription[] codes = new CodeDescription[]{new CodeDescription("M","Male","Gender"),new CodeDescription("F","Female","Gender"),new CodeDescription("S","Single","MaritalStatus"),new CodeDescription("M","Married","MaritalStatus"),new CodeDescription("CN","China","Country"),new CodeDescription("US","Unite States","Country"),new CodeDescription("UK","Britain","Country"),new CodeDescription("SG","Singapore","Country")};public static Collection GetCodes(string category){Collection codeCollection = new Collection();foreach(var code in codes.Where(code=>code.Category == category)){codeCollection.Add(code);}return codeCollection;}}

  

在默认的HomeController中,我们定义了如下两个Index方法,它们分别用于测试出栈数据(Model->UI)入栈数据(UI-〉Model)的绑定。

1: public class HomeController : Controller

2: {

3: public ActionResult Index()

4: {

5: return View(new Person { Name = "Foo", Gender = "M", MaritalStatus = "S", Country = new string[]{"CN","US"} });

6: }

7: [HttpPost]

8: public ActionResult Index(Person person)

9: {

10: return this.View(person);

11: }

12: }

下面是Index操作对应的View的定义,这是一个Model类型为Person的强类型View。对于Person的三个基于列表的属性,我们分别调用了自定义的扩展方法RadioButtonListFor和CheckBoxListFor进行了绑定。方法的最后两个参数分别代表通过CodeManager维护的列表的组别(Gender、MaritalStatus和Country),和同组RadioButton和CheckBox布局方向(水平或者纵向)。

1: @using System.Web.UI.WebControls

2: @model Person

3: @{

4: ViewBag.Title = "Index";

5: }

6: @using (Html.BeginForm())

7: {

8:

9:

10:

11:

12:

13:

14:

15:

16:

17:

18:

19:

20:

21:

22:

23:

24:

25:

26:

27:

28:

@Html.LabelFor(m => m.Name): @Html.EditorFor(m => m.Name)
@Html.LabelFor(m => m.Gender): @Html.RadioButtonListFor(m => m.Gender, "Gender")
@Html.LabelFor(m => m.MaritalStatus): @Html.RadioButtonListFor(m => m.MaritalStatus, "MaritalStatus")
@Html.LabelFor(m => m.Country): @Html.CheckBoxListFor(m => m.Country, "Country", RepeatDirection.Vertical)

29: }

下面是最终呈现出来的效果:

image

三、两组扩展方法具体实现

现在我们简单地来看看RadioButtonList/RadioButtonListFor和CheckBoxList/CheckBoxListFor这两组扩展方法的实现。我们通过CodeManager得到列表集合,通过HtmlHelper结合 ModelMetadata得到当前数据,最终借助于ListControlUtil的GenerateHtml生成相关的Html。

1: public static class ListControlExtensions

2: {

3: public static MvcHtmlString RadioButtonList(this HtmlHelper htmlHelper, string name, string codeCategory, RepeatDirection repeatDirection = RepeatDirection.Horizontal)

4: {

5: var codes = CodeManager.GetCodes(codeCategory);

6: return ListControlUtil.GenerateHtml(name, codes, repeatDirection,"radio",null);

7: }

8: public static MvcHtmlString RadioButtonListFor(this HtmlHelper htmlHelper, Expression> expression, string codeCategory, RepeatDirection repeatDirection = RepeatDirection.Horizontal)

9: {

10: var codes = CodeManager.GetCodes(codeCategory);

11: ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);

12: string name = ExpressionHelper.GetExpressionText(expression);

13: string fullHtmlFieldName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);

14: return ListControlUtil.GenerateHtml(fullHtmlFieldName, codes, repeatDirection, "radio", metadata.Model);

15: }

16: 

17: public static MvcHtmlString CheckBoxList(this HtmlHelper htmlHelper, string name, string codeCategory, RepeatDirection repeatDirection = RepeatDirection.Horizontal)

18: {

19: var codes = CodeManager.GetCodes(codeCategory);

20: return ListControlUtil.GenerateHtml(name, codes, repeatDirection, "checkbox", null);

21: }

22: public static MvcHtmlString CheckBoxListFor(this HtmlHelper htmlHelper, Expression> expression, string codeCategory, RepeatDirection repeatDirection = RepeatDirection.Horizontal)

23: {

24: var codes = CodeManager.GetCodes(codeCategory);

25: ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);

26: string name = ExpressionHelper.GetExpressionText(expression);

27: string fullHtmlFieldName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);

28: return ListControlUtil.GenerateHtml(fullHtmlFieldName, codes, repeatDirection, "checkbox", metadata.Model);

29: }

30: }

ListControlUtil中生成相关Html的逻辑定义如下:

1: public static class ListControlUtil

2: {

3: public static MvcHtmlString GenerateHtml(string name, Collection codes, RepeatDirection repeatDirection, string type, object stateValue)

4: {

5: TagBuilder table = new TagBuilder("table");

6: int i = 0;

7: bool isCheckBox = type == "checkbox";

8: if (repeatDirection == RepeatDirection.Horizontal)

9: {

10: TagBuilder tr = new TagBuilder("tr");

11: foreach (var code in codes)

12: {

13: i++;

14: string id = string.Format("{0}_{1}", name, i);

15: TagBuilder td = new TagBuilder("td");

16: 

17: bool isChecked = false;

18: if (isCheckBox)

19: {

20: IEnumerable currentValues = stateValue as IEnumerable;

21: isChecked = (null != currentValues && currentValues.Contains(code.Code));

22: }

23: else

24: {

25: string currentValue = stateValue as string;

26: isChecked = (null != currentValue && code.Code == currentValue);

27: }

28: 

29: td.InnerHtml = GenerateRadioHtml(name, id, code.Description, code.Code, isChecked,type);

30: tr.InnerHtml += td.ToString();

31: }

32: table.InnerHtml = tr.ToString();

33: }

34: else

35: {

36: foreach (var code in codes)

37: {

38: TagBuilder tr = new TagBuilder("tr");

39: i++;

40: string id = string.Format("{0}_{1}", name, i);

41: TagBuilder td = new TagBuilder("td");

42: 

43: bool isChecked = false;

44: if (isCheckBox)

45: {

46: IEnumerable currentValues = stateValue as IEnumerable;

47: isChecked = (null != currentValues && currentValues.Contains(code.Code));

48: }

49: else

50: {

51: string currentValue = stateValue as string;

52: isChecked = (null != currentValue && code.Code == currentValue);

53: }

54: 

55: td.InnerHtml = GenerateRadioHtml(name, id, code.Description, code.Code, isChecked, type);

56: tr.InnerHtml = td.ToString();

57: table.InnerHtml += tr.ToString();

58: }

59: }

60: return new MvcHtmlString(table.ToString());

61: }

62: 

63: private static string GenerateRadioHtml(string name, string id, string labelText, string value, bool isChecked, string type)

64: {

65: StringBuilder sb = new StringBuilder();

66: 

67: TagBuilder label = new TagBuilder("label");

68: label.MergeAttribute("for", id);

69: label.SetInnerText(labelText);

70: 

71: TagBuilder input = new TagBuilder("input");

72: input.GenerateId(id);

73: input.MergeAttribute("name", name);

74: input.MergeAttribute("type", type);

75: input.MergeAttribute("value", value);

76: if (isChecked)

77: {

78: input.MergeAttribute("checked", "checked");

79: }

80: sb.AppendLine(input.ToString());

81: sb.AppendLine(label.ToString());

82: return sb.ToString();

83: }

84: }

 

通过对HtmlHelper扩展简化“列表控件”的绑定 
为HtmlHelper添加一个RadioButtonList扩展方法 
在ASP.NET MVC中使用“RadioButtonList”和“CheckBoxList”







转:https://www.cnblogs.com/haiyabtx/archive/2012/03/16/2400262.html



推荐阅读
  • 开发笔记:Xunit测试使用个人小结
    篇首语:本文由编程笔记#小编为大家整理,主要介绍了Xunit测试使用个人小结相关的知识,希望对你有一定的参考价值。因工作中用到xunit测试,故总结下用法,以供个人参考使 ... [详细]
  • 这篇文章将为大家详细讲解有关C#开发技巧有哪些,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。C#开发技 ... [详细]
  • PyQt 如何创建自定义QWidget
    这篇文章主要介绍了PyQt如何创建自定义QWidget,帮助大家更好的理解和学习使用pyqt,感 ... [详细]
  • selenium 定位方式3css_selector
    关于页面元素定位,可以根据id、class、name属性以及link_text。其中id属性是最理想的定位方式,class与name属性, ... [详细]
  • 调用:视图调用:1@Html.DropDownListFor(tt.HrEmpGuid,ViewData[Emp] as SelectList, new {@class   ... [详细]
  • 每次用到v-charts我都一阵头疼,因为明明是相同的功能,但是我好像每次用到的解决方法都不一样??每次都是在api中各种查,各种尝试…直到做了个各种数据图形的需求,决定还是好好整 ... [详细]
  • 本文整理了Java中com.google.gwt.user.client.ui.RootPanel.detachOnWindowClose方法的一些代码示例,展示了 ... [详细]
  • 在实际开发中,现在安卓端和后台之间的数据交互,一般都是用JSON来传递数据信息。JSON大家一般都比较熟悉。我这边就以实际项目中的后台传过来的情况和大家分析下及如何处理。比如后台返 ... [详细]
  • 开发笔记:sql盲注之报错注入(附自动化脚本)
    篇首语:本文由编程笔记#小编为大家整理,主要介绍了sql盲注之报错注入(附自动化脚本)相关的知识,希望对你有一定的参考价值。 ... [详细]
  • Mysql MySqlBulkLoader在.NET平台下的批量插入
    批量导入publicboolTranBatchImpo ... [详细]
  • 上次我们总结了React代码构建后的webpack模块组织关系,今天来介绍一下Babel编译JSX生成目标代码的一些规则,并且写一个简单的解析器,模拟整个生成的过程。我们还是拿最简 ... [详细]
  • C#按值复制数组我有一个类型化的数组MyType[]types;我想制作这个数组的独立副本。我试过这个MyType[]types2newMyType[types.Length];t ... [详细]
  • Sets和数组一样,都是一些有序值的的集合,但是Sets和数组又有所不同,首先Sets集合中不能存有相同的值,如果你向Set ... [详细]
  • 这篇文章主要介绍“CSS浮动和定位属性介绍”,在日常操作中,相信很多人在CSS浮动和定位属性介绍问题上存在疑惑,小编查阅了各式资料,整理出简单 ... [详细]
  • NGUIusingSystem;usingUnityEng ... [详细]
author-avatar
平凡骁
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有