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?
You can transfer value from controller using ViewData[""] . ViewData["hdnFlag"] = userId; return View(); Now, In you view.
In jQuery to set a hidden field value, we use . val() method. The jQuery . val() method is used to get or set the values of form elements such as input, select, textarea.
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;
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With