简体   繁体   English

使用HTML.EditorFor Vs使用HTML.CheckBox

[英]Using HTML.EditorFor Vs using HTML.CheckBox

I have the following model class which contains a bool value:- 我有以下模型类,其中包含bool值: -

Public class Server
{
        public bool IsIPUnique { get; set; }
}

Currently i am using the following to display the check box inside my Razor view:- 目前我使用以下内容显示我的Razor视图中的复选框: -

<input type="CheckBox" name="IsIPUnique" value="true" @(Html.Raw(Model.IsIPUnique ? "checked=\"checked\"" : ""))/> IP Unique.

but i read about the EditorFor template, and it can automatically create the check box and check/uncheck it based on the model values so i tried the following :- 但我读到了关于EditorFor模板,它可以自动创建复选框并根据模型值检查/取消选中它,所以我尝试了以下方法: -

@Html.EditorFor(model=>model.IsIPUnique)<span>test</span>

so my question is if i can replace my old code with the new one that uses the EditorFor ?, or asp.net mvc might deal with these values differently ? 所以我的问题是,如果我可以用使用EditorFor的新代码替换我的旧代码,或者asp.net mvc可能会以不同的方式处理这些值? Thanks 谢谢

Basically you have 3 possibilities: 基本上你有3种可能性:

Write HTML manually (as you have done) 手动编写HTML(正如您所做)

I would avoid writing the HTML manually if there is a HTML helper available. 如果有可用的HTML助手,我会避免手动编写HTML。 Manually written HTML is prone to errors which can cause problems with model binding. 手动编写的HTML容易出错,这可能会导致模型绑定出现问题。

Use the specific HTML helpers (Html.CheckBoxFor) 使用特定的HTML帮助程序(Html.CheckBoxFor)

The specific HTML helpers add a layer of abstraction to all controls. 特定的HTML帮助程序为所有控件添加了一个抽象层。 It's easy to modify the template of all controls that use the same HTML helper and it makes your views more readable. 修改使用相同HTML帮助程序的所有控件的模板很容易,它使您的视图更具可读性。

Use the general EditorFor 使用通用EditorFor

The EditorFor HTML helper is great if your model datatypes change often. 如果模型数据类型经常更改,则EditorFor HTML帮助程序非常有用。 The EditorFor will adjust the input fields automatically to the new datatype and won't throw an error (as with the specific HTML helpers). EditorFor会自动将输入字段调整为新的数据类型,并且不会抛出错误(与特定的HTML帮助程序一样)。 It is also a bit harder to add HTML attributes to the EditorFor while the specific HTML helpers often have overloads for them. 将HTML属性添加到EditorFor也有点困难,而特定的HTML帮助程序通常会有重载。 However, this is fixed in MVC 5.1: http://weblogs.asp.net/jongalloway/looking-at-asp-net-mvc-5-1-and-web-api-2-1-part-3-bootstrap-and-javascript-enhancements 但是,这已在MVC 5.1中修复: http//weblogs.asp.net/jongalloway/looking-at-asp-net-mvc-5-1-and-web-api-2-1-part-3-bootstrap -and-JavaScript的增强功能

Conclusion : in your case I would use the CheckBoxFor HTML helper because the datatype won't change likely and it will make the view cleaner 结论 :在你的情况下,我会使用CheckBoxFor HTML帮助器,因为数据类型不会发生变化,它会使视图更清晰

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM