ger*_*rod 7 c# model-view-controller asp.net-mvc
假设我有一个为学生提供搜索功能的控制器:
public class StudentSearchController
{
[HttpGet]
public ActionResult Search(StudentSearchResultModel model)
{
return View(model);
}
}
Run Code Online (Sandbox Code Playgroud)
只要为搜索操作提供了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);
}
}
Run Code Online (Sandbox Code Playgroud)
(假设两个模型都扩展了StudentSearchResultModel.)
我显然不能这样做,因为我无法将预先实例化的模型类传递给搜索控制器(原始搜索控制器将重新创建StudentSearchResultModel,而不是使用传递的模型).
到目前为止我提出的最佳解决方案是将SearchView.cshtml移动到"Shared"文件夹中,然后我可以直接从Uni/HighSchool控制器渲染视图(而不是调用"RedirectToAction").这很好用,理论上我根本不需要StudentSearchController.但是,我正在构建遗留代码(在这个人为的示例中,StudentSearchController是遗留的),所以没有进行大量的重构,"共享"文件夹对我来说不是一个选项.
另一个解决方案是将所有与搜索相关的操作放入StudentSearchController中 - 因此它将为UniStudentSearch和HighSchoolStudentSearch获取两个操作.我不喜欢这种方法,因为这意味着StudentSearchController需要知道它的所有预期用法.
有任何想法吗?
PS:不反对重构,但受到截止日期的限制!
您可以在调用View()的过程中放置视图的路径
return View("~/Views/StudentSearch/SearchView.cshtml", model);
Run Code Online (Sandbox Code Playgroud)