.net 将复选框选择传递到操作
我有一组复选框,用于用户指定他们希望在网格上看到的列: 目前,每个复选框都有自己的键(本质上是它的标签名),在我的视图中声明如下:.net 将复选框选择传递到操作,.net,asp.net-mvc,.net,Asp.net Mvc,我有一组复选框,用于用户指定他们希望在网格上看到的列: 目前,每个复选框都有自己的键(本质上是它的标签名),在我的视图中声明如下: @Html.CheckBox(column.Key, (Request.Form[column.Key] == null ? true : Request.Form[column.Key].Contains("true")), new { @class = "column
@Html.CheckBox(column.Key,
(Request.Form[column.Key] == null ? true :
Request.Form[column.Key].Contains("true")),
new { @class = "columnSelector" })
@Html.Label(column.HeaderText)
问题是我必须在操作中从表单集合获取值,否则我必须为每个列选择器复选框设置一个bool
参数。或者,我想我可以将它们全部命名为“columnselection”或其他名称,然后它将作为一个值数组传递给我的操作,但是由于我没有column键,因此我丢失了值的上下文
我不想为每个复选框创建一个带有属性的viewmodel,因为此功能在其他具有不同列的屏幕上使用,我希望保持通用性
有没有想过如何以简洁明了的方式实现这个专栏选择的功能?这个
Html.CheckBox
方法有一个奇怪的实现。复选框将具有唯一的名称
,本质上是一个真/假
值。这样,该值将很容易映射到动作中的bool
参数
正如您明显注意到的,当您的复选框是动态的时,这会导致一种棘手的情况
解决方案是生成您自己的复选框,所有复选框都使用通用的名称
,并且具有唯一的值
s。这些将很好地映射到您的行动中
以下是所需的操作:
public ActionResult SetSelectedColumns(string[] selectedColumns) {
// selectedColumns will contain the keys of all the checked columns.
}
下面是如何使HTML正确映射:
<input type="checkbox" name="selectedColumns" value="@column.Key" @(column.Selected ? "checked='checked'" : "") />
是的,这就是我现在要走的路。你能详细说明一下你答案中的扩展方法部分吗?@link664我为你写了一个扩展方法!享受:)
public static HtmlString CheckBoxAlt(this HtmlHelper html, string name, string value, bool selected, object htmlAttributes)
{
var tag = new TagBuilder("input");
if (htmlAttributes != null)
tag.MergeAttributes(new RouteValueDictionary(htmlAttributes));
tag.MergeAttribute("type", "checkbox");
tag.MergeAttribute("name", name);
tag.MergeAttribute("value", value);
// Determine if this check should be selected:
var state = html.ViewData.ModelState[name];
if (state != null)
{
var values = (string[])state.Value.ConvertTo(typeof(string[]));
selected = Array.IndexOf(values, value) != -1;
}
if (selected)
tag.MergeAttribute("checked", "checked");
return new HtmlString(tag.ToString(TagRenderMode.SelfClosing));
}