Reputation: 10193
How do you set the MaxLength and Size of a TextBox in MVC 2? There have been a couple of questions asked about this on SO. As a newcomer to MVC I am finding that none of the solutions appear to work - possibly because I am not doing it right.
In any case I am wondering if there are better solutions since the previous questions appear to be asked at a time when MVC 2 was in beta.
Upvotes: 8
Views: 12216
Reputation: 1
The above solution works but if you have multiple instances of that field, it would be easier to set it in the Model or View Model. Be careful with modifying the actual Model because they can be volatile when updating.
Example: In the model or view model.
[DisplayName("Notes")]
[MaxLength(500, ErrorMessage="Maximum length of notes field is 500 characters...")]
[DataType(DataType.MultilineText)]
public string Notes { get; set; }
To have it validate on submit, you would need the following in your web.config.
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
Make sure you reference the validation JS files somewhere, preferably in Shared/_Layout or on the page itself...
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
Lastly make sure that you include the validation message in the cshtml.
@Html.EditorFor(model => model.Notes, new { htmlAttributes = new { @class = "form-control", rows = "5", @placeholder = "Notes", title = "Enter any notes..." } })
@Html.ValidationMessageFor(model => model.Notes, "", new { @class = "text-danger" })
Build the solution and test. Hope this helps anyone else searching for a solution.
Upvotes: 0
Reputation: 9755
It's easy, you just to have extra htmlAtttributes
<%= Html.TextBoxFor(model => model.Member, new { maxlength = "20", width = "15" }) %>
<%= Html.TextBoxFor(model => model.Member, new { maxlength = "20", style = "width:200px;" }) %>
Upvotes: 12