batwadi
batwadi

Reputation: 1906

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

Again stupid question struggling to assign a value for a javascript variable from controller ?

what is the proper way to assign value to a variable below line of code is failing .. Please advice

  var tenmp= '<%= Model.Temp%>';

Upvotes: 4

Views: 5364

Answers (2)

griegs
griegs

Reputation: 22760

I've just tried the same as you and it works fine.

<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 the above assumes that you are trying to get a model value into javascript from your view.

Also, ensure that your view is inheriting from your model else it'd have no idea what temp is.

Hope this is of help.

Upvotes: 4

Ravi Vanapalli
Ravi Vanapalli

Reputation: 9942

You don't need to write, use <% in controllers.

You would probably be using it in aspx/ ascx pages, something like

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

if you are using in aspx or ascx page then directly use

<% var tenmp= Model.Temp; %>

Upvotes: 0

Related Questions