Passing values between ASP.NET and JavaScript

Stefan Prodan edited this page Aug 29, 2014 · 3 revisions

There are two collections available that you can use for passing various settings between your application and the front-end.

You can modify these collections using RequireJsOptions.Add. There are two scopes available, global (the values will be found in requireConfig.websiteOptions) and page (the values will be found in requireConfig.pageOptions).

It is often times useful to always have some values that don't change passed to the front-end. To accomplish this, you can call the RequireJsOptions.Add method from a filter or using controller inheritance.

Please note that the collections are stored in the current request's Items hashset, so attempting to set any options outside of a thread that has a request attached will result in an exception.

Example

Set global options using an action filter:

public class RequireOptionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var url = new UrlHelper(filterContext.RequestContext);
        RequireJsOptions.Add("globalUrlViaFilter", url.Action("Index", "Contact"), RequireJsOptionsScope.Global);
    }
}

Set page options inside an action:

public ActionResult Index()
{
    RequireJsOptions.Add("ids", new[] { 1, 2, 3 }, RequireJsOptionsScope.Page);
    return View();
}

Read both options inside the js code-behind module:

require([
], function () {

    var indexPage = function () {
        //read global options sent by RequireOptionFilter
        console.log("Website Options: " + requireConfig.websiteOptions.globalUrlViaFilter);
        //read page options, sent by HomeController.Index
        console.log("Page Options: " + requireConfig.pageOptions.ids);
    };
});
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.