【发布时间】:2012-02-09 04:06:08
【问题描述】:
假设我有一个为学生提供搜索功能的控制器:
public class StudentSearchController
{
[HttpGet]
public ActionResult Search(StudentSearchResultModel model)
{
return View(model);
}
}
只要为 Search 操作提供了 StudentSearchResultModel,它就会呈现一个搜索结果列表。
有没有办法从另一个控制器有效地扩展此操作方法?例如,假设我想要其他需要搜索学生的控制器,如下所示:
public class UniStudentController
{
[HttpPost]
public ActionResult Search(UniStudentSearchResultModel model)
{
return RedirectToAction("Search", "StudentSearch", model);
}
}
public class HighSchoolStudentController
{
[HttpPost]
public ActionResult Search(HighSchoolSearchResultModel model)
{
return RedirectToAction("Search", "StudentSearch", model);
}
}
(假设两个模型都扩展了 StudentSearchResultModel。)
我显然不能这样做,因为我无法将预先实例化的模型类传递给搜索控制器(原始搜索控制器将重新创建一个 StudentSearchResultModel,而不是使用传递的模型)。
到目前为止,我想出的最佳解决方案是将 SearchView.cshtml 移动到“Shared”文件夹中,然后我可以直接从 Uni/HighSchool 控制器渲染视图(而不是调用“RedirectToAction”)。这很好用,理论上我根本不需要 StudentSearchController。但是,我在这里构建的是遗留代码(在这个人为的示例中,StudentSearchController 是遗留代码),因此如果不进行大量重构,“Shared”文件夹对我来说不是一个选项。
另一种解决方案是将所有与搜索相关的操作放入 StudentSearchController - 这样它将为 UniStudentSearch 和 HighSchoolStudentSearch 获得两个操作。不过我不喜欢这种方法,因为这意味着 StudentSearchController 需要了解其预期用途的所有。
有什么想法吗?
PS:不反对重构,但受限于deadline!
【问题讨论】:
标签: c# asp.net-mvc model-view-controller