问题
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:
- Never put semicolon at the end of @ViewBag.myVariable
- 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