且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

.net MVC Html.CheckBoxFor 的正确使用

更新时间:2023-11-18 12:26:22

这不是正确的语法

第一个参数是不是复选框值,而是复选框的视图模型绑定,因此:

@Html.CheckBoxFor(m => m.SomeBooleanProperty, new { @checked = "checked" });

第一个参数必须标识模型中的布尔属性(它是一个 表达式 不是返回值的匿名方法)并且第二个属性定义了任何附加的 HTML 元素属性.我不是 100% 确定上述属性最初会检查您的复选框,但您可以尝试.但要小心.即使它可以工作,您以后可能会遇到问题,当加载有效的模型数据并且该特定属性设置为 false 时.

正确的方法

尽管我正确的建议是为您的视图提供初始化模型,并将该特定布尔属性初始化为 true.

属性类型

根据 Asp.net MVC HtmlHelper 扩展方法和内部工作,复选框需要绑定到布尔值而不是整数,这似乎是您想要做的.在这种情况下,隐藏字段可以存储 id.

其他帮手

当然,您还可以使用其他辅助方法来获得有关复选框值和行为的更大灵活性:

@Html.CheckBox("templateId", new { value = item.TemplateID, @checked = true });

注意: checked 是一个 HTML 元素布尔属性,而不是一个 value 属性,这意味着您可以将任何值分配给它.正确的 HTML 语法不包括任何赋值,但无法提供具有未定义属性的匿名 C# 对象,该对象将呈现为 HTML 元素属性.

All I want to know is the proper syntax for the Html.CheckBoxFor HTML helper in ASP.NET MVC.

What I'm trying to accomplish is for the check-box to be initially checked with an ID value so I can reference it in the Controller to see if it's still checked or not.

Would below be the proper syntax?

@foreach (var item in Model.Templates) 
{ 
    <td> 
        @Html.CheckBoxFor(model => true, item.TemplateId) 
        @Html.LabelFor(model => item.TemplateName)
    </td> 
}

That isn't the proper syntax

The first parameter is not checkbox value but rather view model binding for the checkbox hence:

@Html.CheckBoxFor(m => m.SomeBooleanProperty, new { @checked = "checked" });

The first parameter must identify a boolean property within your model (it's an Expression not an anonymous method returning a value) and second property defines any additional HTML element attributes. I'm not 100% sure that the above attribute will initially check your checkbox, but you can try. But beware. Even though it may work you may have issues later on, when loading a valid model data and that particular property is set to false.

The correct way

Although my proper suggestion would be to provide initialized model to your view with that particular boolean property initialized to true.

Property types

As per Asp.net MVC HtmlHelper extension methods and inner working, checkboxes need to bind to boolean values and not integers what seems that you'd like to do. In that case a hidden field could store the id.

Other helpers

There are of course other helper methods that you can use to get greater flexibility about checkbox values and behaviour:

@Html.CheckBox("templateId", new { value = item.TemplateID, @checked = true });

Note: checked is an HTML element boolean property and not a value attribute which means that you can assign any value to it. The correct HTML syntax doesn't include any assignments, but there's no way of providing an anonymous C# object with undefined property that would render as an HTML element property.