I am using normal helper EditFor to bind data to html controls.
For completeness, here a example:
@Html.EditorFor(model => model.Description, new { htmlAttributes = new { @maxlength= 100, @class = "form-control" } })
To set maxlength for string fields, i need to explicitly set the attribute in every view that uses the same table field and there are many views and strings value in the data model.
Doing this in every page is error prone. Changes is size will break the app if a place is forgotten.
How to pass the length directly from EF Model?
The easiest option is to add the
[MaxLength(50)]attribute to the model property. For example:You can then omit the
maxlengthproperty from the call to@Html.EditorFor()and it will be taken from the model metadata.