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:
$('#MyHiddenId').val(someNr);
directly, it should be somewhere after your html tag creation otherwise it can't see the hidden. 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.