Take for instance the following code for Edit action in my controller:
// POST: /Admin/Text/Edit/5
[HttpPost]
[ValidateInput(false)]
public virtual ActionResult Edit(TextViewModel editing)
{
if (!ModelState.IsValid)
return View(editing);
Text existing = _repository.Find(editing.Id);
if (TryUpdateModel(existing)) {
_repository.Update(existing);
if(Request.IsAjaxRequest())
return Content(bool.TrueString);
else
return RedirectToAction(pndng.Admin.Text.List());
}
else return View(editing);
}
What I want this action to do is handle both classic (non AJAX form) and AJAX (jquery) POSTs. In case of AJAX POST it is very likely that the request is coming from an inline edit form. In this case, the action should just return the Content=Ok result. In case we have been editing the model in a form page and performed a classic postback we want to redirect the user back to the content List (see RedirectToAction()).
However, the thing bothering me is the if..else clause. I would like to abstract this away into an action filter/attribute. I would like to leave in the redirection call (as this is the default) but have the action filter to act upon it if it detects that the request was in fact AJAX request, meaning stop the redirection and just return the ContentResult or JsonResult.
Also feel free to respond if you think my workflow is wrong.
You should be to implement a custom ResultFilter to do what you want, by implementing IResultFilter. something like:
And then decorate that action with
[AjaxOverrideFilter].This should override the result if its an ajax request and the result type was a redirect… At least, this should give you a push in the right direction. I’m not wildly convinced that this is a great architectural approach though…