Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC Html.TextBoxFor MaxLength and Value

Tags:

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!

like image 390
Baxter Avatar asked Jul 29 '14 18:07

Baxter


People also ask

How do I set the MaxLength for HTML TextBoxFor in MVC?

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.

What is the difference between HTML TextBox and HTML TextBoxFor?

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.

What is the difference between TextBoxFor and EditorFor in MVC?

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.

What is TextBoxFor in MVC?

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.


1 Answers

This should work in MVC4. Not sure about MVC2.

@Html.TextBoxFor(t => t.ProjectDetails.Title,new { @maxlength="10", @class="myCssClass"}) 
like image 66
Shyju Avatar answered Sep 28 '22 02:09

Shyju