Eugene Goldberg
Eugene Goldberg

Reputation: 15544

How to pass data from a controller action to JavaScript function

In my MVC 5 app, in the Home controller's Index() action I'm reading a value from a Web.config variable:

 public ActionResult Index()
        {
           var environment = System.Configuration.ConfigurationManager.AppSettings["Environment"];
...
}

I need to pass that value onto a JavaScript function, which runs when Home/Index.cshtml is rendered:

$(document).ready(function () {
if environment == "External" - pseudo code
    $("#AccessInstanceListItem").hide();
});

How can I accomplish this?

P.S. Ideally, I would like to pass this value to a script, which runs when_layout.cshtml is rendered, but I do not have any controllers associated with the layout view.

Upvotes: 2

Views: 1080

Answers (1)

SivaRajini
SivaRajini

Reputation: 7375

You can use ViewBag fetaure in MVC.

public ActionResult Index()
        {
           ViewBag.environment  = System.Configuration.ConfigurationManager.AppSettings["Environment"];
...
}

script:

$(document).ready(function () {

if environment == '@ViewBag.environment' - pseudo code
    $("#AccessInstanceListItem").hide();
});

refer other info from below link.

viewbag in jquery

refer Darin answer.

Upvotes: 1

Related Questions