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

狂风中的少年 提交于 2019-12-18 13:31:36

问题


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, that are for editing a different models. However, most of those models have a 'name' field. I am looking to be able to specify an editorfor with a specific id as such:

    <div class="editor-label">
        @Html.LabelFor(model => model.Name)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Name,  new {id = "PersonName"})
        @Html.ValidationMessageFor(model => model.Name)
    </div>

I have tried various other things but have not found a satisfactory way to handle this. The two choices I seem to have are:

1) Create a form manually using the normal html helpers and construct the model in the controller

2) Rename all the fields in the model to fit the format

Neither of these are exciting to me so I am hoping for an alternative but am afraid that the id is what is used when binding the form to a model.


回答1:


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"})



回答2:


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.




回答3:


Based on bob's comment :

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

Credits to Bob.




回答4:


Alternatively you can add htmlAttributes

@Html.EditorFor(Model => Model.myField, new { htmlAttributes = new { @class = "form-control", @id = "txtMyField" } })


来源:https://stackoverflow.com/questions/16847209/change-id-attribute-of-an-html-editorfor-helper-in-mvc4-with-razor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!