Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 281
user1765862 Avatar asked Nov 20 '15 11:11

user1765862


People also ask

How do you set the value of a hidden field from a controller in MVC?

You can transfer value from controller using ViewData[""] . ViewData["hdnFlag"] = userId; return View(); Now, In you view.

How do you set the value above the hidden field?

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.


2 Answers

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;
like image 157
Perfect28 Avatar answered Oct 06 '22 23:10

Perfect28


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;

like image 40
Chetan Sharma Avatar answered Oct 06 '22 23:10

Chetan Sharma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!