I am trying to setup a TextBox control in my project using Html.TextBoxFor.
However, it only seems to have method signatures for either:
Lambda Expression and Value:
<%= Html.TextBoxFor(t => t.ProjectDetails.Title, Model.ProjectDetails.Title)%>
or
Lambda Expression and HtmlAttributes:
<%= Html.TextBoxFor(t => t.ProjectDetails.Title, new { maxlength = 10})%>
This is not an issue for styling as the control id is known: ProjectDetails_Title and a style sheet can be used. However, maxlength cannot be set via CSS as it is a behavior.
I know you can specify all three using Html.Textbox but I want to take advantage of the extra functionality of Html.TextBoxFor.
Any ideas on how I can set both a value AND a maxlength for a control rendered using Html.TextBoxFor?
Thanks for any help on this!
The TextBox for the Name value is created using Html. TextBoxFor function while the TextBox for the Mobile Number value is created using Html. TextBox helper function. The MaxLength of both the TextBoxes is set using the HTML MaxLength attribute using the HtmlAttributes parameter in Html.
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.
TextBoxFor: It will render like text input html element corresponding to specified expression. In simple word it will always render like an input textbox irrespective datatype of the property which is getting bind with the control. EditorFor: This control is bit smart.
TextBoxFor<TModel,TProperty>(HtmlHelper<TModel>, Expression<Func<TModel,TProperty>>, Object) Returns a text input element for each property in the object that is represented by the specified expression, using the specified HTML attributes.
This should work in MVC4. Not sure about MVC2.
@Html.TextBoxFor(t => t.ProjectDetails.Title,new { @maxlength="10", @class="myCssClass"})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With