Is there a way to set which div the partial view is loaded into depending on which view is returned from the MVC action? For example an MVC controller action could return one of two views (View A or View B) depending on some logic. If 'View A' is returned then in the done function of the Ajax call load it into 'div A', but if 'View B' is returned then I load it into 'div B'.
public ActionResult SomeActionMethod()
{
if (someCondition == true) {
return PartialView("ViewA", new SomeModel());
}
else {
return PartialView("ViewB", new AnotherModel());
}
}
.done(function(data) {
if (isViewA === true) { // How do I determine which view it is?
$('#div-a').html(data);
} else {
$('#div-b').html(data);
}
})
Is there an known/accepted way to do this (how to determine if it's View A or View B)? I've thought of two ways to do this but both seem a little hacky. If there is no commonly accepted/approved way of doing this then are the following ideas okay...
Idea 1:
Search returned html for a unique element or hidden input value only found in that view. This isn't as easy as it first sounds since the returned data isn’t just simple html but some sort of nested string/object (not really sure). For top level elements the jQuery 'filter' method needs to be used:
$(data).filter('#unique-element');
Otherwise the 'find' method should be used.
Idea 2:
In the controller action, for one of the views being returned (View A), set Response.StatusCode to a custom value in the 200's range that isn’t already used (not 200-208, 226). Then in the ajax done function specify all 3 parameters and check the third parameters status property to compare to the response status you set in the controller action.
if (someCondition == true) {
Response.StatusCode = 299;
return PartialView("ViewA", new SomeModel());
}
else {
return PartialView("ViewB", new AnotherModel());
}
.done(function(data, textStatus, jqXHR) {
if (jqXHR.status === 299) {
// It’s View A so load it into div A
}
else {
// It’s View B so load it into div B
}
})
This works like a charm but seems even more hacky than Idea 1.