Change id attribute for html.editorfor helper in MVC4 using Razor

I looked at several different answers related to this, but they were all for mvc3 or not for Razor.

I have one page with several forms, in partial views, which are designed to edit different models. However, most of these models have a name field. I am looking to be able to specify an editorfor with a specific identifier 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 tried different things, but did not find a satisfactory way to handle this. I seem to have two options:

1) Create a form manually using regular html helpers and build the model in the controller

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

None of them excite me, so I hope for an alternative, but I'm afraid that id is what is used when binding the form to the model.

+4
source share
4 answers

Change the helper from EditorFor to TextBoxFor in the editor, it has no overload to override html properties

Change it

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

To that

 @Html.TextBoxFor(model => model.Name, new {id = "PersonName"}) 
+17
source

I understand that this is a bit late, but I just ran into this problem myself ... I thought: โ€œThere must be a way to use EditorFor and still override the identifierโ€ ... there is. Do the following, and your input will have an identifier and a name for what you like.

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

Hope this helps and hopes it helps other people.

Note: from what I understand, the reason why this is usually not done is to avoid conflicting other dynamically created control identifiers and names.

+21
source

Based on bob comment:

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

Loans for Bob.

+2
source

Alternatively you can add htmlAttributes

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

Source: https://habr.com/ru/post/1483686/


All Articles