nik codes

Archive for the category “MVC”

Something Razor Should Learn From JSX

Alright, here’s the thing: I often find the interaction model between Razor Views and ViewModels in ASP.NET MVC to be clumsy and annoying. Recently I’ve searched for ways to make it better, and there don’t seem to be any. This post highlights how I came to the fore mentioned conclusion, a listing of what I’ve tried to make things better, and a proposal for how to improve Razor.

Champion readers of nikcodes.com, please take a gander at what I’m thinking, I’d love to hear your thoughts on all this.

Declare & Proceed

As I’ve learned more about React, Facebook’s JavaScript templating library, my thoughts on coupling Views and ViewModels has been challenged. (For the unfamiliar, React solves many of the same problems as Knockout, but is more similar in style to Razor than Knockout.)

react-opti

To create Views, React (optionally) uses a somewhat contentious super-set of JavaScript they call JSX. JSX mixes declarative XML and HTML literals directly into procedural JavaScript code. Take this simple JSX “Hello World” example for instance:

var HelloMessage = React.createClass({
    render: function() {
        return <div>Hello {this.props.name}</div>;

    }
});
 
React.render(<HelloMessage name="Nik" />, mountNode);

Notice the <div> and <HelloMessage> tags sprinkled into that JavaScript? The argument is that it’s easier to compose Views in a declarative language like XML, so why not provide that power in the same place as the UI logic? Of course, JSX isn’t something a browser natively understands so this all gets “compiled” into something “native”, in this case, standard, run-of-the-mill JavaScript:

var HelloMessage = React.createClass({
    displayName: "HelloMessage",
    render: function () {
        return React.createElement("div"null"Hello "this.props.name);
    }
});
 
React.render(React.createElement(HelloMessage, { name: "Nik" }), mountNode);

The ability to mix declarative and imperative statements together in a single language is nothing new. VB.NET has a very similar feature called XML Literals as well as LINQ (for querying data structures, which C# also has). Heck, the next version of JavaScript, ES6, has support for Template Literals baked right in as well!

What About the Server Side?

React, and front-end JavaScript developers in general, aren’t the only web developers that leverage Views, ViewModels and an MV* architecture though. ASP.NET MVC developers have been using Razor to mix HTML with C# for years now. To be fair, the balance in Razor Views tends to lean more towards the declarative with little “nuggets” of C# logic sprinkled throughout. For example, see this little HelloMessage.cshtml, Razor template:

@model Person
 
<div>Hello @Model.Name</div>

Like the JSX file, this Razor template gets “compiled” into something “native” – C# in this (abridged) case:

[PageVirtualPathAttribute("~/Views/Home/HelloMessage.cshtml")]
public partial class HelloMessage : WebViewPage<Person>
{
    public override void Execute()
    {
        WriteLiteral("<div>Hello ");
        Write(Model.Name);
        WriteLiteral("</div>");
 
    }
}

So let’s stop for a moment and compare JSX to Razor:

JSX Razor
Front-End (Mostly) Back-End (Mostly)
Imperative code (JavaScript) with declarative XML/HTML mixed in. Declarative code (HTML) with imperative C# or VB mixed in.
UI composition, logic and ViewModel contained in same file. UI composition and logic contained in same file.
ViewModel defined in separate class file.
Compiles to native format: JavaScript Compiles to native format: C# or VB

You’ll note that for the most part, JSX is pretty similar to Razor, with a glaring difference about where the ViewModel is defined. I never perceived this to be an issue, until I saw JSX do it a better way.

Pulling Everything Together

Managing ViewModels in Razor and ASP.NET MVC isn’t necessarily difficult, but it certainly isn’t as easy as it is in the React/JSX world. Over time, ASP.NET MVC developers have established well trodden best practices to help manage this disconnect, including:

  1. ViewModels exist as separate classes (as opposed to using the ViewData dictionary).
  2. Each View gets its own explicit ViewModel.
  3. Naming conventions are used to help locate a ViewModel for any given View.

Following these practices mean that, for the most part, ViewModels and Views basically have a one to one relationship and are logically paired together. I tend to believe that if two things go together logically, then it sure would be nice if they go together physically as well.

Unfortunately, Razor does not allow us to declare a nested class inside the View to use as the ViewModel. In fact, it doesn’t allow us to declare a class at all. I know this because this weekend I tried several different ways to make it work. I even tried to leverage the powerful Razor Generator to get something that would pass as co-located Views and ViewModels.

If any reader can come up with a better way to couple the physical location of a View and its ViewModel together, I’d love to hear it in the comments. To me, the nicest solution would be if ViewModel’s could be declared inline with Razor’s @model syntax. Here’s HelloMessage.cshtml again, updated with my proposal:

@model 
{
    public string Name { getset; }
    public int OtherProperty { getset; }
}

<div>Hello @Model.Name</div>

Note, I’m no longer using the @model syntax as it was intended. Typically @model is followed with a type, like “@model Person“. In this proposal, I go directly into declaring what might be thought of as an anonymous class. I could then use that class inside my controller like this:

public ActionResult HelloMessage() 
{
    var model = new HelloMessage.Model { Name = "Nik" };
    return View(model);
}

I think there would be a lot less ceremony in Razor and ASP.NET MVC if it could physically couple Views and ViewModels together, at least in the common use case where that makes sense. If you prefer to keep them separate, or you have a reusable ViewModel, that’s fine too; just with with the familiar “@model {Type}” syntax.

Do you agree? Would you like to see something like this added to Razor? Do you see a way to improve this design, or are there any problems with it? Please let me know!

PerfMatters.Flush now CourtesyFlush

Pluralsight If you like my blog, you’ll love my Pluralsight courses:
Tracking Real World Web Performance
WebPageTest Deep Dive

Its been nearly a month since I released PerfMatters.Flush on NuGet. The library has been getting people talking about performance and thinking how to improve their web applications.

Unfortunately for me, I regretted releasing the library almost instantly, or at least as soon as Mike O’Brien suggested a much better name for it on Twitter:

For the uninitiated, a courtesy flush refers to the first, early flush you do in the restroom to avoid stinking the place up.

banner

My library is basically the same thing, except, in a much more hygienic environment. Flushing your HTTP response early also provides everyone a benefit.

All that to say I’ve decided to rename PerfMatters.Flush to CourtesyFlush. I’ve “redirected” the old package to use the new one, so you don’t need to worry if you were using the old library. In addition, I’ve also added support for .NET 4.0 in this release.

PerfMatters.Flush Goes 1.0!

Pluralsight If you like my blog, you’ll love my Pluralsight courses:
Tracking Real World Web Performance
WebPageTest Deep Dive

In my previous two performance related posts I’ve gone on and on about the benefits of flushing an HTTP response early and how to do it in ASP.NET MVC. If you haven’t read those yet, I recommend you take a quick moment to at least read Flushing in ASP.NET MVC, and if you have a little extra time go through More Flushing in ASP.NET MVC as well.

I think those posts did a decent job of explaining why you’d want to flush early. In this post I’m going to dig into the details of how to flush early using my library, PerfMatters.Flush.

Three Usage Patterns

The core of what you need to know to use PerfMatters.Flush is that I’ve tried to make it easy to use by providing a few different usage models. Pick the one that works best in your scenario, and feel free to mix and match across your application.

1. Attribute Based

The easiest way to use PerfMatters.Flush is via the [FlushHead] action filter attribute, like this:

[FlushHead(Title = "Index")]
public ActionResult Index()
{
      // Do expensive work here
      return View();
}

The attribute can be used alone for HTML documents with a static <head> section. Optionally, a Title property can be set for specifying a dynamic <title> element, which is very common.

2. Code Based

For more complex scenarios, extension methods are provided which allow you to set ViewData or pass along a view model:

public ActionResult About()
{
     ViewBag.Title = "Dynamic title generated at " + DateTime.Now.ToLocalTime();
     ViewBag.Description = "A meta tag description";
     ViewBag.DnsPrefetchDomain = ConfigurationManager.AppSettings["cdnDomain"];

     this.FlushHead();

     // Do expensive work here
     ViewBag.Message = "Your application description page.";
     return View();
}

As you can see, this mechanism allows for very dynamic <head> sections. In this example you could imagine a <title> element, <meta name="description" content="…"> attribute (for SEO purposes) and <link rel="dns-prefetch" href="…"> (for performance optimization) all being set.

3. Global Lambda

Finally, PerfMatters.Flush offers a model to flush early across all your application’s action methods – which simply leverages the same global action filters that have been in ASP.NET MVC for years now:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
     filters.Add(new HandleErrorAttribute());
     filters.Add(new FlushHeadAttribute(actionDescriptor =>
         new ViewDataDictionary<CustomObject>(new CustomObject())
         {
             {"Title", "Global"},
             {"Description", "This is the meta description."}
         }));
}

In this case we pass a Func<ActionDescriptor, ViewDataDictionary> to the FlushHeadAttribute constructor. That function is executed for each action method. This example is pretty contrite since the result is deterministic, but you can see both a custom model (CustomObject) and ViewData in use at the same time.

In real world usage the actionDescriptor parameter would be analyzed and leveraged to get data from some data store (hopefully in memory!) or from an IOC container.

Installation & Setup

Getting up and running with PerfMatters.Flush is as easy as installing the NuGet package.

From there, you’ll want to move everything you’d like to flush out of _Layout.cshtml to a new file called _Head.cshtml (which sits in the same directory). Here’s an example of _Head.cshtml:

<!DOCTYPE html>
<html>
<head>
     <meta charset="utf-8" />
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
     @if (ViewBag.Description != null)
     {
         <meta name="description" content="@ViewBag.Description">
     }
     <title>@ViewBag.Title - My ASP.NET Application</title>
     @Styles.Render("~/Content/css")
     @Scripts.Render("~/bundles/modernizr")
</head>

Here’s its corresponding _Layout.cshtml file:

@Html.FlushHead()
<body>
     <!-- Lots of lovely HTML -->
     <div class="container body-content">
         @RenderBody()
         <hr />
         <footer>
             <p>&copy; @DateTime.Now.Year - My Application</p>
         </footer>
     </div>
     @Scripts.Render("~/bundles/jquery")
     @Scripts.Render("~/bundles/bootstrap")
     @RenderSection("scripts", required: false)
</body>
</html>

Notice the @Html.FlushHead() method on the first line? That’s the magic that stiches this all together. It allows you to use MVC the way your used to on action methods that you don’t want to flush early, and opt-in (via one of the usage model’s described above) when you do.

Wrapping Up

PerfMatters.Flush has been fun for me to work on. It’s currently being used in production on getGlimpse.com and has nicely boosted perceived performance on the pages that do any database queries.

To be honest, I wish that PerfMatters.Flush didn’t have to exist. I’ve asked the ASP.NET team to look into baking first class support for flushing early into the framework, but I don’t foresee that happening for quite awhile. Either way, there are tons of application built in MVC 3, 4 and 5 that can leverage this now.

The project is open source, and the code is hosted on GitHub. I’d love to hear your feedback on ways to make it better and easier to use.

More HTTP Flushing in ASP.NET MVC

Pluralsight If you like my blog, you’ll love my Pluralsight courses:
Tracking Real World Web Performance
WebPageTest Deep Dive

My last post about HTTP flushing in ASP.NET MVC generated quite a bit of buzz and several really good questions. If you haven’t yet, I recommend you read that post before continuing on here. With this post I’ll answer some of the questions that arose about flushing early and offer a few handy tips.

When to Flush?

Steve Souders does a great job of explaining this technique in his book, Even Faster Web Sites, and on his blog, but there still seems to be some confusion about flushing. For example, Khalid Abuhakmeh mentioned that it “seems arbitrary where you would place the flush” and asked:

tweet

While one could certainly flush lots of small chunks of content to the client, and there may be circumstances that call for doing just that, this recommendation is specifically aimed at (1) improving the user’s perceived performance and (2) giving the browser’s parser and network stack a head start to download the assets required to render a page.

Given that, the more content that can be flushed early, before any expensive server side processing (e.g. database queries or service calls), the better. Typically this means flushing just after the </head> tag, or just before the first @RenderSection()/@RenderBody() Razor directive.

Here’s an example of the difference that flushing makes on a waterfall chart displaying network activity:

difference

Notice that in the “Before” image, the two style sheets and one JavaScript file that are referenced in the the <head> section of the page aren’t downloaded until the original HTML file has finished downloading itself. When flushing the <head> section, however, the browser is able to start downloading these secondary resources and rendering any available HTML immediately – providing the user with visual feedback even sooner.

What’s more, if the style sheets contain rules that reference tertiary resources (e.g. background images, sprites or fonts) and the flushed HTML matches one of those rules, the tertiary resources will be downloaded early as well. Ilya Grigorik, a developer advocate that works at Google on the Chrome web performance team, recently wrote an a post about font performance with the tip to optimize the critical rendering path – which flushing directly helps with.

So basically, it’s best to flush as much of the beginning of an HTML response as you can to improve perceived performance and give the browser a head start on downloading not only secondary assets, but often times tertiary ones as well.

How can I See the Improvement?

The effects of flushing early is most easily seen on a waterfall chart. (New to waterfall charts? Check out Tammy Everts’ excellent Waterfalls 101 post.) But how does that correlate to the user’s experience? That’s where Speed Index comes in. Speed Index is currently the best metric we have to measure the perceived performance of a page load. WebPageTest.org measures Speed Index for any given page by doing a series of screen captures of the loading process, analyzing the images over time, and producing the metric.

logo_wpt

compare_progress
Screen captures of a loading page

chart-line-small
Speed Index comparison of two loads

The WebPageTest documentation covers the algorithm for calculating the metric in depth, and offers suggested targets based on the Alexa Top 300K. The lower a site’s Speed Index, the better.

Personally I’ve never seen flushing early increase a page’s Speed Index. In general, I can’t think of a way that it would hurt performance, but you may not need to use the technique if you don’t have anything in the head to download or any server side processing. As always, your mileage may vary and you should test the results on your own site.

What About Compression?

You should still compress your responses, flushing doesn’t change that recommendation! Compression affects the content that is sent to the client (and adds a Content-Encoding: gzip header).

Flushing, on the other hand, affects how the content is sent to the client (and adds a Transfer-Encoding: chunked header.)

headersHTTP Response with Compression and Flushing in Fiddler

The two options are completely compatible with each other. Souders reported some configuration issues with Apache flushing small chunks of content – but, based on my testing,  IIS doesn’t seem to have these problems. Using the default configuration, IIS compresses each chunk of flushed content and sends it to the client immediately.

How do I Debug?

Flushed HTTP responses are really no different that any other HTTP response. That means the in browser F12 development tools and HTTP proxies like Fiddler work as expected.

One caveat worth mentioning though is that Fiddler, by default, buffers text\html responses, which means that when Fiddler is running the benefits of flushing early won’t be observable in the browser. It’s easy enough to fix this though, simply click the “Stream” icon in the Fiddler toolbar, as covered in the Fiddler documentation.

streamIn Stream mode Fiddler immediately releases response chunks to the client

Are There Any Other Considerations?

Since flushing early is done in the name of giving the browser a head start, be sure to provide the browser’s parser everything it needs to efficiently read the HTML document as soon as possible.

Eric Lawrence, ex-product manager for Internet Explorer, has a post detailing the best practices to reduce the amount of work that the parser has to do to understand a web page. Essentially, begin HTML documents like this and the parser will not have to wait or backtrack:

<!DOCTYPE html>
<html>
<head>
     <meta charset="utf-8">
     <meta http-equiv="X-UA-Compatible" content="IE=edge">
     <base /><!-- Optional -->
     <title>...</title>
     <!-- Everything else -->

What’s the Easiest Way to do This?

I’ve created a simple open source project called PerfMatters.Flush that attempts to make flushing early in ASP.NET MVC as simple as possible. It’s still very alpha-y, but it’s already live on the getGlimpse.com homepage. You can play with the bits now, or wait for my follow up post that details how to use it.

Flushing in ASP.NET MVC

Pluralsight If you like my blog, you’ll love my Pluralsight courses:
Tracking Real World Web Performance
WebPageTest Deep Dive

I’ve written a follow up to this post that answers many of the common questions about flushing early. Be sure to check it out.

The Setting

Before the beginning of this decade, Steve Souders released two seminal books on the topic of web performance: High Performance Web Sites and Even Faster Web Sites. The findings and subsequent suggestions that came out of those books changed the face of web development and have been codified into several performance analysis tools including Yahoo YSlow and Google PageSpeed.

High Performance Web Sites Even Faster Web Sites

Most professional web developers that I’ve met over the past five years are familiar with Souder’s recommendations and how to implement them in ASP.NET MVC. To be fair, they aren’t that difficult:

  • HTTP Caching and Content Compression can both be enabled simply via a few settings in web.config.
  • Layout pages make it easy to put stylesheets at the top of a page and scripts at the bottom in a consistent manner.
  • The Microsoft.AspNet.Web.Optimization NuGet package simplifies the ability to combine and minify assets.
  • And so on, and so forth…

The recommendation to “Flush the Buffer Early” (covered in depth in chapter 12 of Even Faster Web Sites), however, is not so easy to implement in ASP.NET MVC. Here’s an explanation of the recommendation from Steve’s 2009 blog post:

Flushing is when the server sends the initial part of the HTML document to the client before the entire response is ready. All major browsers start parsing the partial response. When done correctly, flushing results in a page that loads and feels faster. The key is choosing the right point at which to flush the partial HTML document response. The flush should occur before the expensive parts of the back end work, such as database queries and web service calls. But the flush should occur after the initial response has enough content to keep the browser busy. The part of the HTML document that is flushed should contain some resources as well as some visible content. If resources (e.g., stylesheets, external scripts, and images) are included, the browser gets an early start on its download work. If some visible content is included, the user receives feedback sooner that the page is loading.

A few months ago Steve revisited this guidance and provided examples of the difference that flushing can make to an application’s performance. His post inspired me to try the same on an ASP.NET MVC project that I’m working on, which led to this post.

The Conflict

Since .NET 1.1, ASP.NET has provided a mechanism to flush a response stream to the client with a simple call to HttpResponse.Flush(). This works quite well when you are incrementally building up a response, but the architecture of MVC, with its use of the command pattern, doesn’t really allow for this. (At least not in a clean manner.) Adding a call to Flush() inside a view doesn’t do much good.

@{
     Response.Flush();
}

This is because MVC doesn’t execute the code in the view until all the other work in the controller has completed – essentially the opposite of what the czar of web performance recommends.

The Climax

Because I’m a believer that #PerfMatters, I decided to take matters into my own hands to see if I could do anything better.

First, I realized that I could can get around a few issues by leveraging partial results, manually executing and flushing them, like so:

public ActionResult FlushDemo()
{
       PartialView("Head").ExecuteResult(ControllerContext);
       Response.Flush();

       // do other work
       return PartialView("RemainderOfPage");
}

I think that looks pretty ugly, so I’ve taken things a step farther and removed the cruft around executing the result by creating a base controller with its own Flush() method:

public class BaseController : Controller
{
     public void Flush(ActionResult result)
     {
         result.ExecuteResult(ControllerContext);
         Response.Flush();
     }
}

I think my new Flush() method clarifies the intent in the action method:

public ActionResult FlushDemo()
{
     Flush(PartialView("Head"));

     // do other work
     return PartialView("RemainderOfPage");
}

What I’d really like to be able to do is leverage the yield keyword. Yield seems like the natural language and syntax to express this. I was able to cobble together this example:

public IEnumerable<ActionResult> Test()
{
      yield return PartialView("Header");
      Thread.Sleep(2000); // or other work

      yield return PartialView("Lorem");
      Thread.Sleep(2000); // or other work

      yield return PartialView("Vestibulum");
      Thread.Sleep(2000); // or other work

      yield return PartialView("Sed");
      Thread.Sleep(2000); // or other work

      yield return PartialView("Footer");
}

I got that working with a pretty ugly hack, but leveraging the yield keyword and IEnumerable<ActionResult> like this should theoretically be possible by making a few changes to MVC’s default action invoker, no hack necessary.  Unfortunately, C# throws a few curve balls at this since you can’t combine the usage of yield with async/await – which I think would be a pretty common usage scenario.

The Resolution?

It looks like splitting up a layout file into multiple partial views and using my Flush() helper method is the best that we can do right now.

Unfortunately,

  • Yielding multiple views isn’t currently supported by MVC, and even if it was it would be incompatible with the current C# compiler.
  • Partial views are the best we can get to break up a response into multiple segments – which is painful. It’d be nice if I could ask Razor to render just a section of a layout page, which would reduce the need for partial views.

I’m hoping that the ASP.NET team, or my readers, can come up with a better way to handle flushing in the future, but I wanted to at least walk you through what your options are today.

For those interested, I might pull together some of this thinking into a NuGet package that leverages action filter attributes to simplify the syntax even further. If you like the sounds of that, encourage me on Twitter: @nikmd23

Testing MVC View Names with [CallerMemberName]

We’ve all written ASP.NET MVC controller actions that simply return a view. They tend to look just like this:

public ActionResult Index()
{
   
return View(); }

It’s also fairly common to test those actions to ensure that the proper view is being returned:

public void Should_Return_Index_View(HomeController sut)
{
    
var
actionResult = sut.Index();
    
var viewResult = actionResult as ViewResult
;
   

Assert
.Equal("Index", viewResult.ViewName); }

If you’ve tried this before you know that the above test will fail. Why? Because viewResult.ViewName actually has a value of string.Empty, not Index. MVC doesn’t mind this, because if a view’s name is empty, it simply defaults to use the value of {action} from the route data collection. That unfortunately makes it difficult to ensure the proper view is being returned in tests.

We could re-work our action method to explicitly specify the name of the view returned (return View(“Index”)), but I really like the simplicity of having a default convention for view names. Instead I’ve been leveraging C# 5.0’s new caller information attributes to retain the simplicity of the convention, but still have the view name explicitly set for testing purposes.

To do this I’ve added the following two methods to the base controller that all of my project’s controllers inherit from:

public new ActionResult View([CallerMemberName] string actionMethod = null)
{
    
return base
.View(actionMethod); } public ActionResult View(object model, [CallerMemberName] string actionMethod = null) {
    
return base.View(actionMethod, model); }

Now, when I re-execute the test, it passes. That’s because the actionMethod parameter is automatically set by the compiler to be the name of the calling method, which in this case is Index. I can still pass in an overriding view name whenever I want, and the compiler will just get out of the way. Nifty!

NOTE: I will point out that you may want to consider if you even need to test the name of a ViewResult to begin with. Assuming you do though, I find this technique to be much cleaner than trying to mock out a whole request just to see what the {action} is.

An ASP.NET MVC JSONP ActionResult

JSON with Padding (JSONP) is a slight “hack” to allow for cross origin ajax requests. Instead of making requests the standard ajax way, leveraging XMLHttpRequest, JSONP techniques make requests by writing a <script> tag into the DOM with the src attribute set to the appropriate URL. Because browsers do not limit the origin of scripts loaded via the <script> tag, data, via JavaScript, can be loaded from any of the hundreds of API’s and endpoints that support JSONP.

Consuming JSONP services is ridiculously easy and has had support built into jQuery since version 1.2.

//gist: https://gist.github.com/1944712
$(function () {
    $.ajax({
        dataType: 'jsonp',
        url: 'http://example.com/JSONP/API/',
        success: function (data) {
            console.log(data);
        }
    });
});

In this case, the data that is returned from the server is logged to the browser console, but any JavaScript could be executed.

Enabling JSONP on top of an existing JSON endpoint (server side) is fairly simple. It requires changing the HTTP response content type, and wrapping the resultant JSON string in a JavaScript function call (the padding part).

Unfortunately, ASP.NET MVC does not ship with JSONP support out of the box, but it is easy to add with the great extensibility points available in MVC. Here is an implementation of an MVC ActionResult which would enable any controller to begin to return proper JSONP results.

//gist: https://gist.github.com/1944346
using System;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;

namespace NikCodes.ActionResults
{
    public class JsonpResult : ActionResult
    {
        public string CallbackFunction { get; set; }
        public Encoding ContentEncoding { get; set; }
        public string ContentType { get; set; }
        public object Data { get; set; }

        public JsonpResult(object data):this(data, null){}
        public JsonpResult(object data, string callbackFunction)
        {
            Data = data;
            CallbackFunction = callbackFunction;
        }


        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null) throw new ArgumentNullException("context");

            HttpResponseBase response = context.HttpContext.Response;

            response.ContentType = string.IsNullOrEmpty(ContentType) ? "application/x-javascript" : ContentType;

            if (ContentEncoding != null) response.ContentEncoding = ContentEncoding;

            if (Data != null)
            {
                HttpRequestBase request = context.HttpContext.Request;

                var callback = CallbackFunction ?? request.Params["callback"] ?? "callback";

#pragma warning disable 0618 // JavaScriptSerializer is no longer obsolete
                var serializer = new JavaScriptSerializer();
                response.Write(string.Format("{0}({1});", callback, serializer.Serialize(Data)));
#pragma warning restore 0618
            }
        }
    }
}

This action result simply takes in an object, serializes it using the standard MVC serialization method and wraps it up in a callback function. It supports jQuery’s JSONP implementation transparently. Using it couldn’t be simpler:

//gist: https://gist.github.com/1944913
public ActionResult ActionMethod()
{
    var data = GetDataSomehow();
    return new JsonpResult(data);
    //constructor overload for overriding callback function
    //return new JsonpResult(data, "callback function"); 
}

Of course, cross origin resource sharing (CORS) is much more powerful that JSONP, and will ultimately replace it – but until then, or as long as we have < IE 10, we will still have to leverage this technique.

Download the code, try it out. Let me know if this is valuable enough to put on NuGet.

– By

Post Navigation