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?
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.
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.
IMHO this is a very nice solution to this problem and something I would definitely use.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With