简体   繁体   中英

Using HtmlHelpers in MVC4

I'm going to use MVC4 for my project in future. I doubt using @Html helpers instead of using classic way like this:

@Html.labelfor(....)

or

<label for="xx">name</label>

Is it necessary to use html helpers?

They are exactly what they say they are - helpers. But they do save you on coding time IMO. You picked the LabelFor example to demonstrate your point but let me give you my example. Is it easier to write:

@Html.TextBoxFor(m => m.LastName, new { @class = "input-block-level", placeholder = "Last Name" })
@Html.ValidationMessageFor(m => m.LastName)

Or

<input class="input-block-level" data-val="true" data-val-length="The field Last Name must be a string with a maximum length of 50." data-val-length-max="50" data-val-required="The Last Name field is required." id="LastName" name="LastName" placeholder="Last Name" type="text" value="">
<span class="field-validation-valid" data-valmsg-for="LastName" data-valmsg-replace="true"></span>

In other words, helpers are very useful in keeping the code clean and easy to maintain while saving you coding time in the process.

You use HTML helpers in a view to render HTML content. An HTML helper, in most cases, is just a method that returns a string. You can build an entire ASP.NET MVC application without using a single HTML helper; however, HTML helpers make your life as a developer easier . By taking advantage of helpers, you can build your views with far less work.
In the ASP.NET MVC world, HTML helpers are the equivalent of ASP.NET Web Form controls. Like a Web Form control, an HTML helper enables you to encapsulate the rendering of HTML. However, unlike a Web Form control, HTML helpers are extremely lightweight. For example, an HTML helper does not have an event model and does not use view state.

-- "ASP.NET MVC Framework UNLEASHED" by Stephen Walther

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