开发者

Html.Textbox VS Html.TextboxFor

开发者 https://www.devze.com 2023-03-03 01:41 出处:网络
What is the differenc开发者_如何学运维e between Html.Textbox and Html.TextboxFor?Ultimately they both produce the same HTML but Html.TextBoxFor() is strongly typed where as Html.TextBox isn\'t.

What is the differenc开发者_如何学运维e between Html.Textbox and Html.TextboxFor?


Ultimately they both produce the same HTML but Html.TextBoxFor() is strongly typed where as Html.TextBox isn't.

1:  @Html.TextBox("Name")
2:  Html.TextBoxFor(m => m.Name)

will both produce

<input id="Name" name="Name" type="text" />

So what does that mean in terms of use?

Generally two things:

  1. The typed TextBoxFor will generate your input names for you. This is usually just the property name but for properties of complex types can include an underscore such as 'customer_name'
  2. Using the typed TextBoxFor version will allow you to use compile time checking. So if you change your model then you can check whether there are any errors in your views.

It is generally regarded as better practice to use the strongly typed versions of the HtmlHelpers that were added in MVC2.


The TextBoxFor is a newer MVC input extension introduced in MVC2.

The main benefit of the newer strongly typed extensions is to show any errors / warnings at compile-time rather than runtime.

See this page.

http://weblogs.asp.net/scottgu/archive/2010/01/10/asp-net-mvc-2-strongly-typed-html-helpers.aspx


IMO the main difference is that Textbox is not strongly typed. TextboxFor take a lambda as a parameter that tell the helper the with element of the model to use in a typed view.

You can do the same things with both, but you should use typed views and TextboxFor when possible.


Html.TextBox amd Html.DropDownList are not strongly typed and hence they doesn't require a strongly typed view. This means that we can hardcode whatever name we want. On the other hand, Html.TextBoxFor and Html.DropDownListFor are strongly typed and requires a strongly typed view, and the name is inferred from the lambda expression.

Strongly typed HTML helpers also provide compile time checking.

Since, in real time, we mostly use strongly typed views, prefer to use Html.TextBoxFor and Html.DropDownListFor over their counterparts.

Whether, we use Html.TextBox & Html.DropDownList OR Html.TextBoxFor & Html.DropDownListFor, the end result is the same, that is they produce the same HTML.

Strongly typed HTML helpers are added in MVC2.


Html.TextBox and Html.TextBoxFor are used to create textbox, It will produce same HTML. But the main difference is,

Html.TextBox - is loosly type means we can pass any name whatever we want.

Eg. @Html.TextBox(“Emp Name”)

Html.TextBoxFor - strongly bounded with model properties.

Eg. @Html.TextBoxFor(m => m.EmpName)

0

精彩评论

暂无评论...
验证码 换一张
取 消