Is there an MVC5 model attribute to set the HTML Size and MaxLength attribute?

In the past, I've used a custom class (HtmlProperties) in MVC3 to set razor HTML properties by declaring my model object as shown below.

[HtmlProperties(Size = 1, MaxLength = 2)]
public string MyModelField{ get; set; }

      

Is there an MVC5 equivalent to do something like this without creating your own class?

+3


source to share


1 answer


Well, as far as I know, the ViewModel and Model should n't contain information about how things will be displayed. They should contain only types (for example, field is a string) and requirements (for example, the field is not empty).

Therefore IMHO rendering objects (how the inputs should look like) must be inside the Razor View. Actually MVC5 has added a new option to achieve this - you can pass an object to an object htmlAttributes

argument additionalViewData

when rendering the editor.

@Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control", custom_attribute = "lol" } })

      



This was not possible in MVC3 and MVC4, as several Html Helpers accepted htmlAttributes

as an argument and several Html Helpes only acceptedadditionalViewData

Also I think you should use [MaxLength(int i)]

if you intend to limit the length of the input to the ViewModel (since this will also help MVC check its client and server side)

    [DisplayName("Name")]
    [Required]
    [MaxLength(5)]
    public string Name{ get; set; }

      

+4


source







All Articles