我似乎无法弄清楚如何获取要在我的表单中呈现的字符串列表作为复选框。在这里尝试了各种各样的网站和问题/答案的一些事情,没有运气。
MODEL
var model = new ProjectModel()
{
ProjectType = new List<string>()
{
"Brand Creation",
"Web Design",
"Graphic Design",
"Custom Programming",
"E-Commerce",
"Other"
},
};
查看 - 我尝试过以下方式。
@foreach (var item in Model.ProjectType)
{
@Html.CheckBoxFor(model => true, item)
<br />
}
@foreach (var item in Model.Budget)
{
@Html.CheckBox(item)
<br />
}
答案 0 :(得分:1)
我宁愿使用Enum来显示复选框。我知道这不是你的答案,但你可以考虑这样做。
您必须执行以下步骤&gt;
Enum
[Flags]
public enum ProjectType
{
[Display(Name = "Brand Creation")]
BrandCreation = 1,
[Display(Name = "Web Design")]
WebDesign = 2
}
创建Html扩展方法
public static IHtmlString CheckboxListForEnum<T>(this HtmlHelper html, string name, T modelItems) where T : struct
{
StringBuilder sb = new StringBuilder();
var displayAttributeType = typeof(DisplayAttribute);
foreach (T item in Enum.GetValues(typeof(T)).Cast<T>())
{
FieldInfo field = item.GetType().GetField(item.ToString());
DisplayAttribute attrs = (DisplayAttribute)field.
GetCustomAttributes(displayAttributeType, false).FirstOrDefault();
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", attrs.GetName());
builder.MergeAttribute("name", name);
builder.InnerHtml = attrs.GetName();
sb.Append(builder.ToString(TagRenderMode.Normal));
}
return new HtmlString(sb.ToString());
}
最后在您的视图中
@Html.CheckboxListForEnum("ProjectType", @Model.ProjectType)
获取发布值
public ActionResult Index(FormCollection form)
{
string[] AllStrings = form["ProjectType"].Split(',');
foreach (string item in AllStrings)
{
int value = int.Parse(item);
}
}