Change id attribute of an html.editorfor helper in MVC4 with Razor

前端 未结 4 683
一个人的身影
一个人的身影 2021-01-01 02:16

I have looked through some various answers related to this but all were for mvc3 or not for Razor.

I have a single page that has multiple forms, in partial views, th

相关标签:
4条回答
  • 2021-01-01 02:55

    Change your helper from EditorFor to TextBoxFor the EditorFor, doesn't have a overload to override html properties

    Change this

    @Html.EditorFor(model => model.Name,  new {id = "PersonName"})
    

    To this

    @Html.TextBoxFor(model => model.Name,  new {id = "PersonName"})
    
    0 讨论(0)
  • 2021-01-01 03:01

    Based on bob's comment :

    EditorFor @Html.EditorFor(model => model.FieldName, new { htmlAttributes = new { id = "myuniqueid"} })
    

    Credits to Bob.

    0 讨论(0)
  • 2021-01-01 03:05

    I realise this is somewhat late but I just ran into this problem myself... I thought "there has to be a way to use the EditorFor and still override the ID"... there is. Do the following and your input has an ID and Name of whatever you like.

    @Html.EditorFor(model => model.myField, null, "txtMyField")
    

    Hope this helps and hope it helps other people too.

    Note: from what I understand, the reason this is typically not done is to avoid other, dynamically created controls ID's and Names from conflicting.

    0 讨论(0)
  • 2021-01-01 03:08

    Alternatively you can add htmlAttributes

    @Html.EditorFor(Model => Model.myField, new { htmlAttributes = new { @class = "form-control", @id = "txtMyField" } })
    
    0 讨论(0)
提交回复
热议问题