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?
相关问题
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Carriage Return (ASCII chr 13) is missing from tex
- MVC-Routing,Why i can not ignore defaults,The matc
PartialViewResult and JSONReuslt inherit from the base class ActionResult. so if return type is decided dynamically declare method output as ActionResult.
Flexible approach to produce different outputs based on the request
The
Request.IsAjaxRequest()
method is quite simple: it merely checks the HTTP headers for the incoming request to see if the value of the X-Requested-With header isXMLHttpRequest
, which is automatically appended by most browsers and AJAX frameworks.Custom extension method to check whether the request is for json or not so that we can call it from anywhere, just like the Request.IsAjaxRequest() extension method:
Source : https://www.safaribooksonline.com/library/view/programming-aspnet-mvc/9781449321932/ch06.html#_javascript_rendering
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...
I found a couple of issues implementing MVC ajax GET calls with JQuery that caused me headaches so sharing solutions here.
JsonRequestBehavior.AllowGet
; without this MVC was returning a HTTP 500 error (withdataType: json
specified on the client).cache: false
to the $.ajax call, otherwise you will ultimately get HTTP 304 responses (instead of HTTP 200 responses) and the server will not process your request.Sample JQuery:
Sample MVC code:
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.
This is overloadable so you can also do: