简体   繁体   中英

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?

PS 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM