ASP.NET MVC controller actions that return JSON or partial html

NathanD picture NathanD · Oct 22, 2008 · Viewed 593.4k times · Source

I am trying to create controller actions which will return either JSON or partial html depending upon a parameter. What is the best way to get the result returned to an MVC page asynchronously?

Answer

Haacked picture Haacked · Oct 22, 2008

In your action method, return Json(object) to return JSON to your page.

public ActionResult SomeActionMethod() {
  return Json(new {foo="bar", baz="Blech"});
}

Then just call the action method using Ajax. You could use one of the helper methods from the ViewPage such as

<%= Ajax.ActionLink("SomeActionMethod", new AjaxOptions {OnSuccess="somemethod"}) %>

SomeMethod would be a javascript method that then evaluates the Json object returned.

If you want to return a plain string, you can just use the ContentResult:

public ActionResult SomeActionMethod() {
    return Content("hello world!");
}

ContentResult by default returns a text/plain as its contentType.
This is overloadable so you can also do:

return Content("<xml>This is poorly formatted xml.</xml>", "text/xml");