Can I pass the viewbag value to the jQuery in mvc2

大兔子大兔子 提交于 2019-12-06 12:04:29

ViewBag is only in ASP.NET MVC 3 so you can't use that, but you can use ViewData:

    $('#showdiv').hide();
      if ($("#" + '<%=ViewData["testNumber"]').value == someinteger){      
         $("#showdiv").show();
       }
        else {
            $("#showdiv").hide();
        }
    });
       <div id="showdiv"> Some Calculation </div>

If you are using MVC3 (Doesn't work with 2) you can easily use ViewBag as below, but remember two points that are easy to forget and can cause headache:

  1. Never put semicolon at the end of @ViewBag.myVariable
  2. If you are passing string put " before and after your @ViewBag.myVariable. For example:

This is right:

$(function () {
    var path = "@ViewBag.helpPath"
    path = "@Url.Content("~/route/action/")" + path;
    $('#help-content').load(path);

});

However if you use:

$(function () {
    var path = @ViewBag.helpPath
    path = "@Url.Content("~/route/action/")" + path;
    $('#help-content').load(path);

});

MVC changes this to:

$(function () {
    var path = c:\\doc\\path
    path = "@Url.Content("~/route/action/")" + path;
    $('#help-content').load(path);

});

Which JavaScript cannot parse it, and the result would be some ugly bug. Just something I did and wasted my time thought to share it.

in razor you'd just do @ViewBag.Variable_Name . I do it in my code.

You could do that in your View:

$('#showdiv').hide();
  $('@Viewbag.testNumber').value == someinteger{

    $("#showdiv").show();
    else
    $("#showdiv").hide();
});
   <div id="showdiv"> Some Calculation </div>

For your MVC2 JavaScript just write the variable straight out, obviously you cant use ViewBag so:

var testNumber = <%:ViewData["VariableName"]%>;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!