最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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%>';

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%>';
Share Improve this question asked Feb 26, 2010 at 4:58 batwadibatwadi 1,9267 gold badges30 silver badges42 bronze badges 3
  • This code should work properly. – LukLed Commented Feb 26, 2010 at 5:00
  • This looks fine, are you getting some error or is tenmp empty? – DavGarcia Commented Feb 26, 2010 at 5:16
  • The code looks good. Have you checked the HTML source to see if the value is embedded? Could you provide more details on the problem? Is it because you have a typo on your 'tenmp' var? – David Glenn Commented Feb 26, 2010 at 8:52
Add a ment  | 

2 Answers 2

Reset to default 4

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.

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; %>
发布评论

评论列表(0)

  1. 暂无评论