How to set @ Html.Editor value to use jquery in asp.net mvc

I want to set the value of my input using jquery. I tried to do this:

<div class="editor-label"> @Html.LabelFor(model => model.ID ) </div> <div class="editor-field"> @Html.EditorFor(model => model.ID) @Html.ValidationMessageFor(model => model.ID) </div> 

and jquery syntax:

  $("#ID").val(data.ID); 

But it does not work. I tried the same jquery code with this:

 <input type="text" id="ID" /> 

This approach works, but I don't know why @ Html.EditorFor does not work with jquery. thanks in advance

+4
source share
4 answers

You are better off using the TextBoxFor method, since it allows you to change the identifier and class of an element directly, while EditorFor does not work if you have not created a custom editing state for it (using EditorTemplate).

 @Html.TextBoxFor(model => model.ID, new { id = "ID" }) 

I believe that @Html.EditorFor(model => model.ID) set the name attribute, since it is mvc that depends on its binding to the model, so if this is not to your liking, you can use this name as a selector.

+3
source

You can add @id , @class , etc. on EditorFor as follows:

 @Html.EditorFor(model => model.ID, new {htmlAttributes = new {@id="someid"}}) 
+2
source

it works for me

 <div class="editor-field"> @Html.EditorFor(model => model.ID) @Html.ValidationMessageFor(model => model.ID) </div> <div class="editor-field"> @Html.EditorFor(model => model.SetID) @Html.ValidationMessageFor(model => model.SetID) </div> 

and javascript

 var d = $("#ID ").val(); $("#SetID").val(d); 

or

 $("#SetID").val($("#ID ").val()); 
+1
source

You have to use

 @Html.EditorFor(model => model.ID, new {@id="someid"}) 

Then

 $("#someid").val (someval) 
0
source

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


All Articles