在的CheckBoxList asp.net的MVC [英] checkboxlist in asp.net MVC
问题描述
我想创建asp.net mvc的视图中的CheckBoxList并希望显示工作日(星期一星期二,....)。我想保存由用户在数据库中选择的值(S)。我怎样才能在MVC2做到这一点。
I want to create a checkboxlist in asp.net mvc view and want to display week days (monday tuesday, ....). I want to save the value(s) selected by user in database. How can I do this in MVC2
有人建议我使用这里提到的枚举类型作为位标志:
Someone suggested me to use "Enumeration Types as Bit Flags" mentioned here:
http://msdn.microsoft.com/en-us/library/ cc138362.aspx
我如何使用它?
请提出解决方案。
推荐答案
是的,我会也建议在这种情况下枚举。
Yes i would also suggest an enum in this scenario.
下面是如何在ASP.NET MVC做到这一点:
Here is how you can do it in ASP.NET MVC:
您枚举应该是这样的(看你提供的链接):
Your enum should look like this (see the link you provided):
[Flags]
public enum Days
{
Sunday = 0x1,
Monday = 0x2,
Tuesday = 0x4,
Wednesday = 0x8,
Thursday = 0x10,
Friday = 0x20,
Saturday = 0x40
}
有关的可重用性目的,我创建了一个普通的HTML辅助,看起来像这样:
For reusability purposes I have created an generic html helper that looks like this:
public static IHtmlString CheckboxListForEnum<T>(this HtmlHelper html, string name, T modelItems) where T : struct
{
StringBuilder sb = new StringBuilder();
foreach (T item in Enum.GetValues(typeof(T)).Cast<T>())
{
TagBuilder builder = new TagBuilder("input");
long targetValue = Convert.ToInt64(item);
long flagValue = Convert.ToInt64(modelItems);
if ((targetValue & flagValue) == targetValue)
builder.MergeAttribute("checked", "checked");
builder.MergeAttribute("type", "checkbox");
builder.MergeAttribute("value", item.ToString());
builder.MergeAttribute("name", name);
builder.InnerHtml = item.ToString();
sb.Append(builder.ToString(TagRenderMode.Normal));
}
return new HtmlString(sb.ToString());
}
您可以使用相同的HTML帮助所有枚举类型。
You can use the same html helper for all enumeration types.
现在用于演示目的,让说你有一个这样的模型:
Now for demonstration purposes let say that you have a model like this:
public class TVShow
{
public string Title { get; set; }
public string Description { get; set; }
public Days AvailableOn { get; set; }
}
控制器动作:
public ActionResult Show()
{
var show = new TVShow
{
Title = "Late Late Show",
AvailableOn = Days.Monday | Days.Friday
};
return View(show);
}
查看(强类型):
<%: Model.Title %>
<%: Model.Description %>
<%: Html.CheckboxListForEnum<Days>("days", Model.AvailableOn)%>
这篇关于在的CheckBoxList asp.net的MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!