Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Controller can return either JSON or HTML depending on the result

Suppose I have a pop-up window that contains a form. I must have a controller that processes the form, and depending on the result, this controller returns either JSON (if all goes well, and popup can be closed by javascript) or HTML (if the form data is not valid and form must be replaced with a new html - with the validation error messages). So I found just such a solution: that's form:

<form id="message" ...>
    ...
</form>

And I have jquery handler for this form:

$(document).on("submit", "form#message", function (evt) {
    evt.preventDefault();
    $.ajax({
        type: this.method,
        url: this.action,
        data: $(this).serialize(),
        success: function (result) {
            if ($.isPlainObject(result)) {
                // this is JSON
                // close the pop-up window
            } else {
                // this is HTML
                $("form#message").html(result);
            }
        }
    });
});

Controller:

[HttpPost]
public ActionResult UpdateMessage(MessageModel model)
{
    ...
    if (.. is valided ..)
        return Json(new { success = "OK" });
    else
        return View(model);
}

The question - are there more elegant solutions for such tasks?

like image 379
Don Tomato Avatar asked May 21 '13 06:05

Don Tomato


People also ask

Can we directly return JSON?

Then, behind the scenes, it would put that JSON-compatible data (e.g. a dict ) inside of a JSONResponse that would be used to send the response to the client. But you can return a JSONResponse directly from your path operations.

How do I return JSON from action method?

To return JSON (JavaScript Object Notation) content from controller, we use JsonResult return type in the action method of the controller. In the above code, we are setting the properties of the UserNamePasswordModel object and converting into JSON by Json method and returning to the view.


2 Answers

IMHO this is a very nice solution to this problem and something I would definitely use.

like image 165
Darin Dimitrov Avatar answered Nov 07 '22 05:11

Darin Dimitrov


Look fine with your approach. But if your JSON error message is common for all screens to use, I would like to suggest that you can write a action filter in this case. So we can make a code more elegant

[HttpPost]
[JsonErrorHandling]
public ActionResult UpdateMessage(MessageModel model)
{    
    return View(model);
}

public class JsonErrorHandlingAttribute : ActionFilterAttribute, IActionFilter 
{
   void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
   {
      // TODO: doing some thing magic here
      // if (.. is valided ..)
      //  return Json(new { success = "OK" });

      this.OnActionExecuting(filterContext);
   }
}
like image 24
thangchung Avatar answered Nov 07 '22 05:11

thangchung