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?
up vote
18
down vote
favorite
15
|
|||
|
up vote
22
down vote
accepted
|
In your action method, return Json(object) to return JSON to your page.
Then just call the action method using Ajax. You could use one of the helper methods from the ViewPage such as
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:
ContentResult by default returns a text/plain as its contentType.
|
||||||||||
|
up vote
10
down vote
|
Another nice way to deal with JSON data is using the JQuery getJSON function. You can call the
method from the jquery getJSON method by simply...
|
||
|
up vote
7
down vote
|
NathanD, I think you should consider the AcceptTypes of the request. I am using it in my current project to return the correct content type as follows. Your action on the controller can test it as on the request object
You can then implement the aspx of the view to cater for the partial xhtml response case. Then in jQuery you can fetch it passing the type parameter as json:
Hope this helps James |
||
|
up vote
5
down vote
|
To answer the other half of the question, you can call:
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. |
||
|
up vote
1
down vote
|
You may want to take a look at this very helpful article which covers this very nicely! Just thought it might help people searching for a good solution to this problem. http://weblogs.asp.net/rashid/archive/2009/04/15/adaptive-rendering-in-asp-net-mvc.aspx Paul |
||
|