Life is too important to be take seriously.

Passing values from your ASP.NET MVC Controller to Javascript

Tuesday, December 11, 2012 at 4:05 AM UTC

Inspired by John Papa’s Single Page Application series on Pluralsight, in my latest project I am making heavy use of the JavaScript MVVM pattern.  Since my application isn't a true single page application I found myself in some cases needing use values from my Controller in my JavaScript methods.

After doing some research I came across this post from A. Friedman about Ngon a port he created of the Ruby Gon gem.  Ngon allows you to add a value to a ViewBag NGon property and then consume it in your JavaScript.

To use Ngon I can just add the NGonActionFilterAttribute to my RegisterGlobalFilters

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
   filters.Add(new NGonActionFilterAttribute());
   filters.Add(new HandleErrorAttribute());

So in my controller action I just set the Ngon values.

if (User.Identity.IsAuthenticated)
   ViewBag.NGon.UserName = User.Identity.Name;
   ViewBag.NGon.CurrentUserId = WebSecurity.CurrentUserId;

In my _Layout.cshtml file I added a @using NGon and a @Html.IncludeNGon() to the <head> section.

@using NGon
<!DOCTYPE html>
<html lang="en">
        <meta charset="utf-8" />
        <title>@ViewBag.Title - My ASP.NET MVC Application</title>
        <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
        <meta name="viewport" content="width=device-width" />

And then I can just use the ngon object like this in my JavaScript

activate = function (callback) {

config.currentUserId = ngon.CurrentUserId; config.currentUser = function () { return { id: function () { return ngon.CurrentUserId; } }; };

messenger.publish.viewModelActivated({ canleaveCallback: canLeave }); getActivityItems(callback);


Very elegant solution to the problem.  Ngon is now available as a Nuget package.