maxlength attribute of a text box from the DataAnnotations StringLength in Asp.Net MVC

前端 未结 7 708
攒了一身酷
攒了一身酷 2020-11-30 18:33

I am working on an MVC2 application and want to set the maxlength attributes of the text inputs.

I have already defined the stringlength attribute on the Model objec

7条回答
  •  天涯浪人
    2020-11-30 19:03

    While I'm personally loving jrummel's jquery fix, here's another approach to keeping a single-source-of-truth up in your model...

    Not pretty, but.. has worked o.k. for me...

    Instead of using property decorations, I just define some well-named public constants up in my model library/dll, and then reference them in my view via the HtmlAttributes, e.g.

    Public Class MyModel
    
        Public Const MAX_ZIPCODE_LENGTH As Integer = 5
    
        Public Property Address1 As String
    
        Public Property Address2 As String
    
        
        Public Property ZipCode As String
    
        Public Property FavoriteColor As System.Drawing.Color
    
    End Class
    

    Then, in the razor view file, in the EditorFor... use an HtmlAttirubte object in the overload, supply the desired max-length property and referenece the constant.. you'll have to supply the constant via a fully qualied namespace path... MyCompany.MyModel.MAX_ZIPCODE_LENGTH.. as it won't be hanging right off the model, but, it works.

提交回复
热议问题