MVC Html.TextBoxFor MaxLength and Value

Baxter picture Baxter · Jul 29, 2014 · Viewed 74.6k times · Source

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!

Answer

Shyju picture Shyju · Jul 29, 2014

This should work in MVC4. Not sure about MVC2.

@Html.TextBoxFor(t => t.ProjectDetails.Title,new { @maxlength="10", @class="myCssClass"})