简体   繁体   中英

assigning value from js code to mvc razor's hidden field

if I have inside razor view already defined hidden field like

@Html.HiddenFor(m => m.MyHiddenId)

how can I populate this from inline js code

var someNr = 100;

how to assign this someNr value to m.MyHiddenId property?

Add an explicit id attribute to @Html.HiddenFor

@Html.HiddenFor(m => m.MyHiddenId, new { id = "hat" }) 

Then with jQuery :

var someNr = 100;
$('#hat').val(somNr); 

For those who don't have jQuery

document.getElementById("hat").value = somNr;

According to answers below, without explicit id, HiddenFor will set attribute id to MyHiddenId . So, this will work too :

var someNr = 100;
$('#MyHiddenId').val(someNr);

Or without jQuery :

document.getElementById("MyHiddenId").value = somNr;

MVC will give that field an id of 'MyHiddenId'

So for Jquery you can set it as follows:

$("#MyHiddenId").val(someNr);

First you have to assign ID for you control, By that you know the control ID at compile time .

@Html.HiddenFor(m => m.MyHiddenId, new { id = "MyHiddenId" })

Jquery Code:-

var someNr = 100;

$('#MyHiddenId).val(somNr);

JavaScript Code:-

var someNr = 100;

document.getElementById('MyHiddenId').value = somNr;

You can use:

$(function(){
    var someNr = 100;
    $('#MyHiddenId').val(someNr);
});

Note:

  • It's better to perform assignment in document ready as above. This way it's not important where you put the above code, and it's enough to be after referencing jquery; while if you use $('#MyHiddenId').val(someNr); directly, it should be somewhere after your html tag creation otherwise it can't see the hidden.
    Also if the value is dependent to any other value or if the value relies on an ajax request setting it in the ready is recommended.
  • Since you are using helper, the hidden has id attribute = MyHiddenId and you don't need to set it manually.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM