Noah Blumenthal's Blog

June 17, 2009

jEditable note: don’t return JSON (and how to return strings from ASP.NET MVC Actions)

Filed under: ASP.NET MVC,jQuery — noahblu @ 5:42 pm

jEditable is a cool jQuery plugin for inline editing.  I was toying around with it today and found an interesting ‘feature’: it expects a string response from the server.  Now that’s a problem because I was returning a JSON object so my string had quotes around it (Test became “Test”).  Ok, so I have to return a regular string.  I guess I just didn’t expect that because I’m used to my jQuery plugins expecting json (or at least accepting it).

Well, my Action returns an ActionResult because not always will it be accessed via jQuery (yup, this does not actually require javascript!).  I check the request (if (Request.IsAjaxRequest())) and proceed…
So, what I did was create a StringResult.  Much like the JsonResult class, the StringResult outputs the data you give it but it just outputs text.  Simple but effective, here’s the code:

public class StringResult : ActionResult
 {
 private string _output;
 public StringResult(string output)
 {
 _output = output;
 }
 public override void ExecuteResult(ControllerContext context)
 {
 HttpResponseBase response = context.HttpContext.Response;
 response.ContentType = "text/html";
 response.Write(_output);
 }
 }
Advertisements

2 Comments »

  1. Thanks. There’s already something similar, it’s called ContentResult, and you can ‘return Content(“string”);’ from an action.

    Comment by Elad Ossadon — June 18, 2009 @ 10:04 pm | Reply

    • Hey, that’s cool! I guess I missed that, though I did try to google it… Well, you learn something every day. Thanks!

      Comment by noahblu — June 18, 2009 @ 10:39 pm | Reply


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: