vote up 7 vote down
star
8

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?

flag
add comment

3 Answers:

vote up 6 vote down
check

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.

Phil

link|flag
comments (4)
vote up 4 vote down

Another nice way to deal with JSON data is using the JQuery getJSON function. You can call the

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

method from the jquery getJSON method by simply...

          $.getJSON("../SomeActionMethod", {
                id: someId
            },
            function(data) {
    alert(data.foo);
alert(data.baz);}
link|flag
add comment
vote up 2 vote down

To answer the other half of the question, you can call:

return PartialView("viewname");

when you want to return partial HTML. You'll just have to find some way to decide whether the request wants JSON or HTML, perhaps based on a URL part/parameter.

link|flag
comments (1)

Your Answer:

Get an OpenID
or

Not the answer you're looking for? Browse other questions tagged or ask your own question.