Tag Archives: MVC

Passing values from your ASP.NET MVC Controller to Javascript

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

<span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> RegisterGlobalFilters(GlobalFilterCollection filters)
   filters.Add(<span class="kwrd">new</span> NGonActionFilterAttribute());
   filters.Add(<span class="kwrd">new</span> HandleErrorAttribute());

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

<span class="kwrd">if</span> (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.

@<span class="kwrd">using</span> NGon
&lt;!DOCTYPE html&gt;
&lt;html lang=<span class="str">"en"</span>&gt;
        &lt;meta charset=<span class="str">"utf-8"</span> /&gt;
        &lt;title&gt;@ViewBag.Title - My ASP.NET MVC Application&lt;/title&gt;
        &lt;link href=<span class="str">"~/favicon.ico"</span> rel=<span class="str">"shortcut icon"</span> type=<span class="str">"image/x-icon"</span> /&gt;
        &lt;meta name=<span class="str">"viewport"</span> content=<span class="str">"width=device-width"</span> /&gt;
        @Styles.Render(<span class="str">"~/Content/css"</span>)
        @Scripts.Render(<span class="str">"~/bundles/modernizr"</span>)

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

activate = function (callback) {
   config.currentUserId = ngon.CurrentUserId;
   config.currentUser = function () { <span class="kwrd">return</span> { id: function () { <span class="kwrd">return</span> ngon.CurrentUserId; } }; };
    messenger.publish.viewModelActivated({ canleaveCallback: canLeave });

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