Is there a good convention-based way to avoid repetitive code like the following in my controller action methods?:
if (Request.IsAjaxRequest())
{
return PartialView("EmployeeList", _service.GetEmployees());
}
return RedirectToAction("Index");
Is there a good convention-based way to avoid repetitive code like the following in my controller action methods?:
if (Request.IsAjaxRequest())
{
return PartialView("EmployeeList", _service.GetEmployees());
}
return RedirectToAction("Index");
If all of your Controllers inherit from a base class that you control, you can add that bit of logic in a function there.
Something like:
internal class MyBaseController : Controller
{
protected ActionResult PartialOrRedirect<T>(string partialName, Func<T> getModel, string actionName)
{
if (Request.IsAjaxRequest())
{
return PartialView(partialName, getModel());
}
return RedirectToAction(actionName);
}
}
public class MyDerrivedController : MyBaseController
{
public ActionResult Employees()
{
return PartialOrRedirect(
"EmployeeList",
() => _service.GetEmployees(),
"Index");
}
}
Otherwise, you can consider using an extension method to do the same thing on the Controller
type.