Mr A
Mr A

Reputation: 6778

Can I pass the viewbag value to the jQuery in mvc2

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

Answers (5)

Reza
Reza

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:

  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.

Upvotes: 5

Chris
Chris

Reputation: 3201

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

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

Upvotes: 1

amurra
amurra

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

daniel.herken
daniel.herken

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

maciek
maciek

Reputation: 659

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

Upvotes: 1

Related Questions