Setup:
ASP.NET MVC3, jQuery, C#
Has anyone got a clean solution to handle different partial views returning from the same action method? One for the next stage, one for returning the view again with validation errors and the other for display an unhandled exception.
I have a controller method that does something like:
public ActionResult SomeMethod(MyModel model)
{
if(_service.Validate(model))
{
if(_service.Update(model))
{
// return next view once success
return PartialView("EverythingIsGood"); // This should be pushed into #somediv
}else{
throw new HardException("Tell the client something bad has happened");
}
}
else
{
// Return the same view to highlight the validation errors
HttpContext.Response.StatusCode = 500;
return PartialView("SomeMethod", model); // This should be pushed into #anotherdiv
}
}
Client Script
$.ajax({
url: baseUrl + "Home/SomeMethod",
type: "GET",
success: function (data) {
$("#somediv").html(data);
},
error: function (data) {
handleError(data);
}
});
I guessing I need something like softerror:
$.ajax({
url: baseUrl + "Home/SomeMethod",
type: "GET",
success: function (data) {
$("#somediv").html(data);
},
softerror: function (data) {
$("#anotherdiv").html(data);
},
error: function (data) {
handleError(data);
}
});
I was thinking of maybe returning a different status code for the soft validation errors but this feels hacky.
You can pass one more variable in your response and check it value on client side via js.
something like this:
Controller:
…
and in your javascript: