Can I pass the viewbag value to the jQuery in mvc2

岁酱吖の 提交于 2020-01-02 10:33:55

问题


I need to pass the value to jQuery in the view using viewbag. What I want to achieve is pass the null or some value and then jQuery should hide or show the div depending on the value passed for instance something like below:

viewbag.testNumber = null;
 $('#showdiv').hide();
  $('viewbag.testNumber').value == someinteger{

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

Also I want to disable the viewbag in the view if the value is null , because it gives null error


回答1:


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>



回答2:


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.




回答3:


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




回答4:


You could do that in your View:

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

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



回答5:


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

var testNumber = <%:ViewData["VariableName"]%>;


来源:https://stackoverflow.com/questions/6521286/can-i-pass-the-viewbag-value-to-the-jquery-in-mvc2

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