using viewbag with jquery - asp.net mvc 3

后端 未结 3 1800
轮回少年
轮回少年 2020-12-28 21:38

I have a ViewBag.IsLocal set to true in controller. I would like to use jquery to check the ViewBag value and display an alert.

Code:

if(@ViewBag.IsL         


        
相关标签:
3条回答
  • 2020-12-28 22:12

    Assuming you have set the IsLocal property to a boolean value in your controller action:

    public ActionResult Index()
    {
        ViewBag.IsLocal = true;
        return View();
    }
    

    you could do this on the view:

    <script type="text/javascript">
        @if(ViewBag.IsLocal)
        {
            <text>alert("yeah");</text>
        }
    </script>
    

    And please don't use ViewBag/ViewData. Use view models and strongly typed views.

    So here's a better approach that I prefer. You could JSON serialize your view model into a javascript variable and then deal with it. Like this:

    @model MyViewModel
    
    <script type="text/javascript">
        var model = @Html.Raw(Json.Encode(Model));
        // at this stage model is a javascript variable containing
        // your server side view model so you could manipulate it as you wish
        if(model.IsLocal)
        {
            alert("hello " + model.FirstName);
        }
    </script>
    

    Obviously if you don't need your entire view model you could JSON serialize only a subset of it => only the part that will be needed by client scripts.

    0 讨论(0)
  • 2020-12-28 22:14

    You can use the following function

    function parseBoolean(str)
    { 
       return /^true$/i.test(str);
    }
    

    and Use it as

    if(parseBoolean('@ViewBag.IsLocal') == true) 
    { 
       alert("yeah");
    }
    
    0 讨论(0)
  • 2020-12-28 22:26

    If you view source on the rendered page, what's being inserted in place of your razor nugget? If IsLocal is a bool type, I think you'll see this:

    @if(True == true)
    {
      alert("yeah");
    }
    

    The reason for that is because true.ToString() is True.

    In which case, you'll need to make a string comparison there:

    if('@ViewBag.IsLocal' == 'True')
    {
      alert("yeah");
    }
    
    0 讨论(0)
提交回复
热议问题