Search code examples
javascriptjqueryasp.net-mvcrazorviewbag

How to check ViewBag's property in a cshtml page?


I am working on MVC application and I need to check ViewBag value on cshtml page, how can I do that?

on Controller.cs:

Viewbag.Mode= "EDIT";

I need to check the value from Viewbag.Mode if it is EDIT show alert as EDIT

I am writing this conditional code in JavaScript, what is the syntax to check Viewbag property in cshtml?


Solution

  • You don't get direct access to C# variables in javascript as one is server-side, the other client-side. You need to write the ViewBag value to the HTML output and then interrogate the DOM to find it using javascript. Something like this:

    In your CSHTML:

    @Html.Hidden("Mode", (string)ViewBag.Mode, new { id = "mode" })
    

    In jQuery:

    if ($('#mode').val() == "EDIT") {
        // do something...
    }
    

    You could also wrap the JS code directly in a C# if (ViewBag.Mode == "EDIT") statement in your view, however this is both ugly, and not a good separation of concerns.