ASP.NET MVC: how to hide ActionResult for a string?

I would like to take an existing action method, map its return value to a string, and send it as JSON to respond to an AJAX request.

To do this, I need to display an ActionResult for the row. How to do it?

We have the opposite, where we can convert the string to ActionResult using this.Content ().

Refresh

The existing and first action method returns an ActionResult type, but it does return a ViewResult to respond to the HTTP request. I have a second action method (my facade) that returns a JsonResult that responds to AJAX requests. I want this 2nd action method to use the 1st action method to render HTML.

In a grand scheme of things, I want the ActionResult (generated from the action method) to be retrieved not only by a standard HTTP message, but also by an AJAX request through the facade action method (second action method). So, as a developer, I have the choice of using HTTP mail or AJAX to get the page rendered.

Sorry, I tried to make this update as short as possible. Thanks.

+6
json string asp.net-mvc actionresult actionmethod
source share
3 answers

Are you looking for number 4 or 6 below?

Text extracted from here :

Understanding Action Results

A controller action returns something called the result of the action. The result of the action is the action of the controller in response to a request from the browser.

The ASP.NET MVC framework supports several types of actions, including:

  • ViewResult - Represents HTML and markup.
  • EmptyResult - does not present a result.
  • RedirectResult - Represents a redirect to a new URL.
  • JsonResult - Represents the result of representing a JavaScript object that can be used in an AJAX application.
  • JavaScriptResult - Represents a JavaScript script.
  • ContentResult - represents a text result.
  • FileContentResult - represents a downloadable file (with binary content).
  • FilePathResult - represents a downloadable file (with a path).
  • FileStreamResult - represents a downloadable file (with a file stream).

All these action results are inherited from the ActionResult base class.

+6
source share

Return it as a ContentResult, not an ActionResult

I use something like

public ContentResult Place(string person, string seat) { string jsonString = null; try { jsonString = AllocationLogic.PerformAllocation(person, seat); } catch { jsonString = AllocationLogic.RaiseError(timeout); } return Content(jsonString); } 
+1
source share

Are you sure JsonResult not what you want? If you call the Json(object jsonObject) method, which is defined in the Controller , it serializes the jsonObject into JSON and returns the appropriate response (with all the correct header settings and all that). Usually JSON requests should be POST, but you can configure it to also enable GET.

+1
source share

All Articles