Reputation: 6778
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
Upvotes: 2
Views: 17059
Reputation: 834
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:
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.
Upvotes: 5
Reputation: 3201
For your MVC2 JavaScript just write the variable straight out, obviously you cant use ViewBag so:
var testNumber = <%:ViewData["VariableName"]%>;
Upvotes: 1
Reputation: 15411
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>
Upvotes: 2
Reputation: 1105
You could do that in your View:
$('#showdiv').hide();
$('@Viewbag.testNumber').value == someinteger{
$("#showdiv").show();
else
$("#showdiv").hide();
});
<div id="showdiv"> Some Calculation </div>
Upvotes: 1