Reputation: 3221
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.
Upvotes: 1
Views: 2307
Reputation: 286
You can pass one more variable in your response and check it value on client side via js. something like this: Controller:
if(_service.Update(model))
{
return Json(new {
IsEverythingGood=true;
htmlToShow=PartialView("EverythingIsGood"); // This should be pushed into #somediv
});
}
...
else
{
return return Json(new {
IsEverythingGood=false;
htmlToShow=PartialView("SomeMethod", model); // This should be pushed into #anotherdiv
}
and in your javascript:
success: function (data) {
if(data.IsEverythingGood==true){
$("#somediv").html(data.htmlToShow);
}
else if(data.IsEverythingGood==false){
$("#anotherdiv").html(data.htmlToShow);
}
Upvotes: 3
Reputation: 1733
You can do something like below.
View
$.get("Home/Index", { random: '@DateTime.Now.Ticks' }, function (response,textData,jqXHR) {
// Based on **jqXHR.status** value you can fill value of div
$("#DivName").html(response);
});
Controller
public ActionResult Index(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
}
}
Upvotes: 1