C# 将“名称”属性添加到 CheckBoxFor

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11638191/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 18:37:26  来源:igfitidea点击:

adding "name" attribute to CheckBoxFor

c#asp.net-mvc-3razorentity

提问by user547794

I am trying to add a "name" attribute to my CheckBoxForand can't get it to work.

我正在尝试为我的“名称”属性添加一个“名称”属性CheckBoxFor,但无法使其正常工作。

@Html.CheckBoxFor(
model => model.ProvidePracticalSuggestions, 
new { @name = "help_practicalSuggestions" 
                })

Any idea what I am doing wrong here?

知道我在这里做错了什么吗?

Rendered HTML:

渲染的 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>

采纳答案by Shyju

EDITon 09/07/2016

编辑2016年9月7日

This will not work

这行不通

@Html.CheckBoxFor(model => model.ProvidePracticalSuggestions,
                                              new { name = "help_practicalSuggestions"   })

But This will work

但这会奏效

@Html.CheckBoxFor(model => model.ProvidePracticalSuggestions,
                                              new { Name = "help_practicalSuggestions"   })

The trick is to use capital letter "N"in "Name"

诀窍是"N""Name"



I do not think this is Possible. You can not change the nameattribute for a checkbox element when using the HTML Helper method. Out of curiousity, i looked into the MVC source code and found something interesting inside InputHelpermethod which is being called from the CheckBoxHelpermethod which is being called from the CheckBoxFormethod

我不认为这是可能的name使用 HTML Helper 方法时,您不能更改复选框元素的属性。出于好奇,我查看了 MVC 源代码,发现了一些有趣的内部InputHelper方法,该CheckBoxHelper方法正在从该CheckBoxFor方法调用的方法中调用

enter image description here

在此处输入图片说明

It is calling the MergeAttribute method for "type", "name" and "value". And this code is only for the Checkboxelement

它正在为“ type”、“ name”和“ value”调用 MergeAttribute 方法。并且此代码仅适用于Checkbox元素

EDIT : Looked into the MergeAttribute method and this is how it is

编辑:查看 MergeAttribute 方法,这就是它的方式

public void MergeAttribute(string key, string value)
{
    bool flag = false;
    this.MergeAttribute(key, value, flag);
}

So it is calling MergeAttributeof the TagBuilderclass and it looks like this

因此,它是调用MergeAttribute了的TagBuilder类,它看起来像这样

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");
    }
}

And the the first Ifcondition returns true and the inner ifwill not return true because ( I guess) nameis present in the Attributescollection. So it will just execute the returnstatement.

第一个If条件返回 true 而内部if不会返回 true 因为(我猜)name存在于Attributes集合中。所以它只会执行return语句。

Solution: Instead of using Html.CheckBoxForhelper method, you might use the Html.CheckBoxmethod.

解决方案Html.CheckBoxFor您可以使用该Html.CheckBox方法,而不是使用辅助方法。

public static MvcHtmlString CheckBox(
    this HtmlHelper htmlHelper,
    string name
)

So your code will become

所以你的代码会变成

@Html.CheckBox("help_practicalSuggestions",Model.ProvidePracticalSuggestions)

The first parameter is the name you want for the input element.

第一个参数是您想要的输入元素的名称。

Also, as explained in one of the other answer, If you use new { @Name="MyCustomName"}and It will generate the checkbox element with the name you are passing. But it will not generate the hidden input field with this name. your hidden field will still have the same name as your model property name. CheckboxForhelper method usually generate the hidden fieldto store the selected/unselected value of checkbox in this hidden field. So it is important that you should have both field's(checkbox and it's associated hidden field) name as same.

此外,如其他答案之一所述,如果您使用new { @Name="MyCustomName"}and 它将生成带有您传递的名称的复选框元素。但它不会生成具有此名称的隐藏输入字段。您的隐藏字段仍将与您的模型属性名称具有相同的名称。CheckboxForhelper 方法通常会生成隐藏字段来存储此隐藏字段中复选框的选中/未选中值。因此,重要的是您应该将两个字段的(复选框及其关联的隐藏字段)名称相同。

So the best solution is to use Html.CheckBoxhelper method. This will generate the proper name for the hidden field as well.

所以最好的解决方案是使用Html.CheckBox辅助方法。这也将为隐藏字段生成正确的名称。

回答by Shane Fulmer

Try without the @:

尝试不使用@:

@Html.CheckBoxFor(model => model.ProvidePracticalSuggestions, new { name = "help_practicalSuggestions" })

回答by HatSoft

You don't need the @ symbol in name

您不需要名称中的@ 符号

@Html.CheckBoxFor(
model => model.ProvidePracticalSuggestions, 
new { name = "help_practicalSuggestions" })

回答by Serg Rogovtsev

Can't do that. The whole point of CheckBoxForis to auto-generate name. If you want your own name, use

不能那样做。重点CheckBoxFor是自动生成name. 如果您想要自己的名字,请使用

@Html.CheckBox("help_practicalSuggestions", Model.ProvidePracticalSuggestions)

回答by jschell12

Just create a temp variable and pass that in the lambda expression.

只需创建一个临时变量并将其传递到 lambda 表达式中即可。

@{var help_practicalSuggestions = Model.ProvidePracticalSuggestions; } 
@Html.CheckBoxFor(model => help_practicalSuggestions)

Update

更新

Serg Rogovtsev is actually right. The '...For' version of the helper function provides the name attribute for you automatically.

Serg Rogovtsev 实际上是对的。帮助函数的“...For”版本自动为您提供 name 属性。

回答by Karan

In CheckBoxFor helper we bind the control to property using expression. The property name is used to set the name attribute of the control.

在 CheckBoxFor 助手中,我们使用表达式将控件绑定到属性。属性名称用于设置控件的名称属性。

@Html.CheckBoxFor(model => model.IsMarried)

When I bind the model property with the checkbox, it assigns the name attribute of the control with property name itself as shown below :

当我将模型属性与复选框绑定时,它会使用属性名称本身分配控件的名称属性,如下所示:

Rendered HTML:

渲染的 HTML:

<input id="IsMarried" name="IsMarried" type="checkbox" value="true" />
<input name="IsMarried" type="hidden" value="false" />

You can propbably use CheckBox helper to give name attribute or you can create your own custom helper method where you can assign attributes as you wish.

您可以使用 CheckBox 助手来提供 name 属性,或者您可以创建自己的自定义助手方法,您可以在其中根据需要分配属性。

For more additional information visit :

如需更多信息,请访问:

http://20fingers2brains.blogspot.in/2013/02/html-checkboxfor-helper-in-mvc3-razor.html

http://20finger2brains.blogspot.in/2013/02/html-checkboxfor-helper-in-mvc3-razor.html

回答by tklives

Actually, all you have to do is use "@Name" (with a uppercase N) as shown below, and everything should work out just fine! :)

实际上,您所要做的就是使用“@Name”(带有大写的 N),如下所示,一切都应该很好!:)

@Html.CheckBoxFor(
model => model.ProvidePracticalSuggestions,
         new { @Name = "help_practicalSuggestions"})

Cheers!

干杯!

回答by Rahul

First add filter to your model that called DisplayAttribute

首先向调用的模型添加过滤器 DisplayAttribute

[DisplayAttribute(Name = "Some Text")]
public bool IsChecked { get; set; }

And you can use Label for model

你可以使用标签作为模型

@Html.LabelFor(model => model.PropertyName)