Question: static HTML controls vs razor html helper

Question

static HTML controls vs razor html helper

Answers 1
Added at 2016-12-27 13:12
Tags
Question

i am new to asp.net mvc , as i see asp.net mvc generates @Html.TextBoxFor(x => x.Name) this type of controls. which are server side controls like web forms. as we know that browser knows only HTML so its mean that these controls will be converted to html before rendering in a browser. mean it will take extra time & memory to perform this operation. why not we use simple html controls like <input type='text'>

Answers
nr: #1 dodano: 2016-12-27 13:12

i see asp.net mvc generates @Html.TextBoxFor(x => x.Name) this type of controls. which are server side controls like web forms

No these are not server side controls, these are just strongly typed helper methods for generating html or input controls that are binded with the model.

why not we use simple html controls like <input type='text'>

Because asp.net mvc has a concept of Model Binder which binds the model with the controller action on the http post, when form is posted back from client browser, so for example, you have a viewmodel which posts some information to the control action, for example, consider following Model:

public class User
{

    public string Login {get;set;}
    public string Password {get;set;}

}

Now if you write plain html, you would need to write it like:

<input type="text"  name="Login" />
<input type="password" name="Password"/>

But let's say for some reason in future you rename the property in your model to UserName from Login, what will happen?

It will break your view code, or for example some other developer form the team changes that, the plain html will contain wrong name of input control, which will cause failures and will take time to find and fix, while if you have used Strongly typed helper methods, changing the property name will cause compile time error in the View, as it will not be able to find the definition of Login in User class.

Source Show
◀ Wstecz