代码之家  ›  专栏  ›  技术社区  ›  Neil Barnwell

ASP.NETmvcajax/局部视图和DRY

  •  1
  • Neil Barnwell  · 技术社区  · 14 年前

    if (Request.IsAjaxRequest())
    {
        return PartialView("EmployeeList", _service.GetEmployees());
    }
    return RedirectToAction("Index");
    
    1 回复  |  直到 14 年前
        1
  •  1
  •   John Gietzen    14 年前

    比如:

    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");
        }
    }
    

    否则,可以考虑使用扩展方法在 Controller 类型。