Question

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?

Was it helpful?

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.

OTHER TIPS

it's simple.. just use @Razor syntax in ViewPage

@if(ViewBag.Mode=="Edit")
{
 //here you show the alert thing
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top