asp.net-mvc .net MVC Html.CheckBoxFor 的正确使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12674572/
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
Proper usage of .net MVC Html.CheckBoxFor
提问by sagesky36
All I want to know is the proper syntax for the Html.CheckBoxForHTML helper in ASP.NET MVC.
我只想知道Html.CheckBoxForASP.NET MVC 中 HTML 助手的正确语法。
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.
我想要完成的是首先使用 ID 值检查复选框,以便我可以在控制器中引用它以查看它是否仍然被选中。
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>
}
回答by Robert Koritnik
That isn't the proper syntax
这不是正确的语法
The first parameter is notcheckbox 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 Expressionnot 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.
第一个参数必须标识模型中的布尔属性(它是一个表达式,而不是返回值的匿名方法),第二个属性定义任何其他 HTML 元素属性。我不是 100% 确定上述属性最初会检查您的复选框,但您可以尝试。但要小心。即使它可能工作,您稍后可能会遇到问题,当加载有效的模型数据并且该特定属性设置为false.
The correct way
正确的方法
Although my proper suggestionwould be to provide initialized model to your view with that particular boolean property initialized to true.
尽管我的正确建议是为您的视图提供初始化模型,并将该特定布尔属性初始化为true.
Property types
物业类型
As per Asp.net MVC HtmlHelperextension 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.
根据 Asp.net MVCHtmlHelper扩展方法和内部工作,复选框需要绑定到布尔值而不是整数,这似乎是您想要做的。在这种情况下,隐藏字段可以存储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:
checkedis 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.
注意:
checked是一个 HTML 元素布尔属性而不是 value 属性,这意味着您可以为其分配任何值。正确的 HTML 语法不包括任何赋值,但无法提供具有未定义属性的匿名 C# 对象,该对象将呈现为 HTML 元素属性。
回答by T Gupta
By default, the below code will NOTgenerate a checked Check Box as model properties override the html attributes:
默认情况下,以下代码不会生成选中的复选框,因为模型属性会覆盖 html 属性:
@Html.CheckBoxFor(m => m.SomeBooleanProperty, new { @checked = "checked" });
Instead, in your GET Actionmethod, the following needs to be done:
相反,在您的GET Action方法中,需要执行以下操作:
model.SomeBooleanProperty = true;
The above will preserve your selection(If you uncheck the box) even if model is not valid(i.e. some error occurs on posting the form).
即使模型无效(即发布表单时发生一些错误),上述内容也会保留您的选择(如果您取消选中该框)。
However, the following code will certainly generate a checked checkbox, but will not preserve your uncheck responses, instead make the checkbox checked every time on errors in form.
但是,以下代码肯定会生成一个选中的复选框,但不会保留您取消选中的响应,而是每次在表单中出现错误时都选中该复选框。
@Html.CheckBox("SomeBooleanProperty", new { @checked = "checked" });
UPDATE
更新
//Get Method
public ActionResult CreateUser(int id)
{
model.SomeBooleanProperty = true;
}
Above code would generate a checked check Box at starting and will also preserve your selection even on errors in form.
上面的代码会在开始时生成一个选中的复选框,并且即使在表单错误时也会保留您的选择。
回答by Kirk Liemohn
I was having a problem with ASP.NET MVC 5 where CheckBoxFor would not check my checkboxes on server-side validation failure even though my model clearly had the value set to true. My Razor markup/code looked like:
我在使用 ASP.NET MVC 5 时遇到问题,其中 CheckBoxFor 不会在服务器端验证失败时检查我的复选框,即使我的模型显然将值设置为 true。我的 Razor 标记/代码如下所示:
@Html.CheckBoxFor(model => model.MyBoolValue, new { @class = "mySpecialClass" } )
To get this to work, I had to change this to:
为了让它起作用,我不得不将其更改为:
@{
var checkboxAttributes = Model.MyBoolValue ?
(object) new { @class = "mySpecialClass", @checked = "checked" } :
(object) new { @class = "mySpecialClass" };
}
@Html.CheckBox("MyBoolValue", checkboxAttributes)
回答by James Gray
Place this on your model:
把它放在你的模型上:
[DisplayName("Electric Fan")]
public bool ElectricFan { get; set; }
private string electricFanRate;
public string ElectricFanRate
{
get { return electricFanRate ?? (electricFanRate = "/month"); }
set { electricFanRate = value; }
}
And this in your cshtml:
这在你的 cshtml 中:
<div class="row">
@Html.CheckBoxFor(m => m.ElectricFan, new { @class = "" })
@Html.LabelFor(m => m.ElectricFan, new { @class = "" })
@Html.DisplayTextFor(m => m.ElectricFanRate)
</div>
Which will output this:
这将输出:
If you click on the checkbox or the bold label it will check/uncheck the checkbox
如果您单击复选框或粗体标签,它将选中/取消选中复选框
回答by Craig Trombly
None of the above answers worked for me when binding back on POST, until I added the following in CSHTML
在绑定回 POST 时,上述答案均不适合我,直到我在 CSHTML 中添加以下内容
<div class="checkbox c-checkbox">
<label>
<input type="checkbox" id="xPrinting" name="xPrinting" value="true" @Html.Raw( Model.xPrinting ? "checked" : "")>
<span class=""></span>Printing
</label>
</div>
// POST: Index
[HttpPost]
public ActionResult Index([Bind(Include = "dateInHands,dateFrom,dateTo,pgStatus,gpStatus,vwStatus,freeSearch,xPrinting,xEmbroidery,xPersonalization,sortOrder,radioOperator")] ProductionDashboardViewModel model)
回答by Yvette
I had trouble getting this to work and added another solution for anyone wanting/ needing to use FromCollection.
我在让它工作时遇到了麻烦,并为任何想要/需要使用 FromCollection 的人添加了另一个解决方案。
Instead of:
代替:
@Html.CheckBoxFor(model => true, item.TemplateId)
Format html helper like so:
像这样格式化 html helper:
@Html.CheckBoxFor(model => model.SomeProperty, new { @class = "form-control", Name = "SomeProperty"})
Then in the viewmodel/model wherever your logic is:
然后在您的逻辑所在的视图模型/模型中:
public void Save(FormCollection frm)
{
// to do instantiate object.
instantiatedItem.SomeProperty = (frm["SomeProperty"] ?? "").Equals("true", StringComparison.CurrentCultureIgnoreCase);
// to do and save changes in database.
}
回答by Ali Adravi
I was looking for the solution to show the label dynamically from database like this:
我正在寻找从数据库动态显示标签的解决方案,如下所示:
checkbox1 : Option 1 text from database
checkbox2 : Option 2 text from database
checkbox3 : Option 3 text from database
checkbox4 : Option 4 text from database
So none of the above solution worked for me so I used like this:
所以上述解决方案都不适合我,所以我是这样使用的:
@Html.CheckBoxFor(m => m.Option1, new { @class = "options" })
<label for="Option1">@Model.Option1Text</label>
@Html.CheckBoxFor(m => m.Option2, new { @class = "options" })
<label for="Option2">@Mode2.Option1Text</label>
In this way when user will click on label, checkbox will be selected.
这样当用户点击标签时,复选框将被选中。
Might be it can help someone.
可能它可以帮助某人。

