Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass Model field value into a javascript variable?

Tags:

asp.net-mvc

<%: Html.HiddenFor(model => model.Name) %>


<script> 
var name = <%: Model.Name %> 
alert(name);
</script> 

like image 915
h3n Avatar asked Aug 13 '10 11:08

h3n


1 Answers

You need to put quotes around the value so that it is considered as a string:

var name = '<%: Model.Name %>';
alert(name);

But if you already have the value inside a hidden field:

<%: Html.HiddenFor(model => model.Name) %>

you could read it like this:

var name = document.getElementById('Name').value; // make sure the id is Name
alert(name);

or using jquery:

var name = $('#Name').val();
alert(name);
like image 176
Darin Dimitrov Avatar answered Oct 27 '22 02:10

Darin Dimitrov