我正在尝试向我的CheckBoxFor添加一个"name“属性,但无法使其工作。
@Html.CheckBoxFor(
model => model.ProvidePracticalSuggestions,
new { @name = "help_practicalSuggestions"
})你知道我做错了什么吗?
呈现的HTML:
<div>
<input data-val="true" data-val-required="The Provide practical suggestions for implementing change, e.g. step-by-step best practices field is required." id="ProvidePracticalSuggestions" name="ProvidePracticalSuggestions" type="checkbox" value="true" /><input name="ProvidePracticalSuggestions" type="hidden" value="false" />
<span class="field-validation-valid" data-valmsg-for="ProvidePracticalSuggestions" data-valmsg-replace="true"></span>
<label for="ProvidePracticalSuggestions">Provide practical suggestions for implementing change, e.g. step-by-step best practices</label>
</div>发布于 2012-07-25 04:07:42
在2016年9月7日编辑
这将不起作用
@Html.CheckBoxFor(model => model.ProvidePracticalSuggestions,
new { name = "help_practicalSuggestions" }),但这将会起作用
@Html.CheckBoxFor(model => model.ProvidePracticalSuggestions,
new { Name = "help_practicalSuggestions" })诀窍是在"Name"中使用大写字母"N"
我不认为这是可能的,。使用HTML Helper方法时,不能更改checkbox元素的name属性。出于好奇,我查看了MVC源代码,在从CheckBoxHelper方法调用的InputHelper方法中发现了一些有趣的东西,该方法是从CheckBoxFor方法调用的

它为"type“、"name”和"value“调用MergeAttribute方法。此代码仅适用于复选框元素
EDIT :查看了MergeAttribute方法,它是这样的
public void MergeAttribute(string key, string value)
{
bool flag = false;
this.MergeAttribute(key, value, flag);
}因此,它调用TagBuilder类的MergeAttribute,如下所示
public void MergeAttribute(string key, string value, bool replaceExisting)
{
if (!string.IsNullOrEmpty(key))
{
if (replaceExisting || !this.Attributes.ContainsKey(key))
{
this.Attributes[key] = value;
}
return;
}
else
{
throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "key");
}
}第一个If条件返回true,内部if不会返回true,因为(我猜) name存在于Attributes集合中。所以它只会执行return语句。
解决方案:可以使用Html.CheckBox方法,而不是使用Html.CheckBoxFor帮助器方法。
public static MvcHtmlString CheckBox(
this HtmlHelper htmlHelper,
string name
)所以你的代码将会变成
@Html.CheckBox("help_practicalSuggestions",Model.ProvidePracticalSuggestions)第一个参数是您希望输入元素的名称。
此外,正如其中一个other answer中所解释的,如果您使用new { @Name="MyCustomName"},它将使用您传递的名称生成checkbox元素。但它不会生成名为的隐藏输入字段。隐藏字段的名称仍与模型属性名称相同。CheckboxFor帮助器方法通常使用generate the hidden field来存储此隐藏字段中复选框的选中/未选中的值。因此,重要的是你应该让这两个字段(复选框及其关联的隐藏字段)的名称相同。
所以最好的解决方案是使用Html.CheckBox帮助器方法。这也将为隐藏字段生成正确的名称。
发布于 2012-07-25 04:06:54
我不能这么做。CheckBoxFor的全部意义在于自动生成name。如果您想要自己的名字,请使用
@Html.CheckBox("help_practicalSuggestions", Model.ProvidePracticalSuggestions)发布于 2013-08-22 05:36:47
实际上,您所要做的就是使用"@Name“(带有大写的N),如下所示,一切都应该很好!:)
@Html.CheckBoxFor(
model => model.ProvidePracticalSuggestions,
new { @Name = "help_practicalSuggestions"})干杯!
https://stackoverflow.com/questions/11638191
复制相似问题