【问题标题】:Sharing views between controllers without using the Shared folder在不使用 Shared 文件夹的情况下在控制器之间共享视图
【发布时间】: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


    【解决方案1】:

    您可以将视图的路径放在对 View() 的调用中

    return View("~/Views/StudentSearch/SearchView.cshtml", model);
    

    【讨论】:

    • 真;但是 SearchView 依赖于其他视图(例如 @Html.Partial("Controls/Student")),如果您采用这种方法,则无法找到这些视图。
    • 考虑到您希望 SearchView 以这种方式由多个控制器共享,您还必须更精确地处理视图内的这些调用。 @Html.Partial("~/Controls/Student")
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-05
    • 1970-01-01
    • 2018-01-23
    • 1970-01-01
    • 1970-01-01
    • 2011-05-11
    • 1970-01-01
    相关资源
    最近更新 更多