简体   繁体   中英

Using HTML.EditorFor Vs using HTML.CheckBox

I have the following model class which contains a bool value:-

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

Currently i am using the following to display the check box inside my Razor view:-

<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 :-

@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 ? Thanks

Basically you have 3 possibilities:

Write HTML manually (as you have done)

I would avoid writing the HTML manually if there is a HTML helper available. Manually written HTML is prone to errors which can cause problems with model binding.

Use the specific HTML helpers (Html.CheckBoxFor)

The specific HTML helpers add a layer of abstraction to all controls. It's easy to modify the template of all controls that use the same HTML helper and it makes your views more readable.

Use the general EditorFor

The EditorFor HTML helper is great if your model datatypes change often. The EditorFor will adjust the input fields automatically to the new datatype and won't throw an error (as with the specific HTML helpers). It is also a bit harder to add HTML attributes to the EditorFor while the specific HTML helpers often have overloads for them. 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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