How to assign javascript variable value from MVC asp.net controller

Again a silly question trying to assign a value to a javascript variable from a controller?

What is the correct way to assign a value to a variable below a line of code does not work .. Please advice

var tenmp= '<%= Model.Temp%>'; 
+4
source share
2 answers

I just tried the same thing as you and it works great.

 <script language="javascript"> var a = '<%=Model.userName %>'; alert(a); </script> 

In my controller, I have the following:

 public ActionResult Login() { LoginFormViewModel loginFVM = new LoginFormViewModel(); loginFVM.userName = "slappy"; return View(loginFVM); } 

All of the above assumes that you are trying to get the model value in javascript from your view.

Also, make sure your view inherits from your model, otherwise it would not know what temp is.

Hope this helps.

+4
source

You do not need to write, use <% in controllers.

You are probably using it on aspx / ascx pages, something like

 <input type="hidden" class="pnum" value="<%=PageNum%>" /> 

if you use aspx or ascx on the page, then use

 <% var tenmp= Model.Temp; %> 
0
source

Source: https://habr.com/ru/post/1302450/


All Articles