如果您想根据方法在视图中包含不同的内容,那么就这样做并使用两个视图。然后,您可以将部分用于相关内容以保留 DRY。
像这样分离视图的一个主要优点是您使依赖项(在本例中为ViewBag 变量)更加清晰。在您的示例中,您必须一直深入到 javascript 中才能发现可能需要一些时间的细节。根据经验,我总是尽量让自己的观点保持愚蠢(即完成任务所需的逻辑尽可能少)。
例如:
Controllers/ExampleController.cs:
public ActionResult Index ( )
{
//...
return View("View1");
}
[HttpPost]
public ActionResult Index (HttpPostedFileBase file, string selectedOrgName, string selectedCatName)
{
//...
ViewBag.orgcatJSON = "some json string";
return View("View2");
}
视图/示例/View1.cshtml:
<h1>View 1</h1>
<!-- specific content here -->
<!-- now include shared content -->
@Html.Partial("SharedContent")
视图/示例/View2.cshtml:
<h1>View 2</h1>
<!-- specific content here -->
<!-- now include shared content -->
@Html.Partial("SharedContent")
<script>
var ogmap = @Html.Raw(ViewBag.orgcatJSON);
$(function() {
//functionality here
});
</script>
视图/示例/SharedContent.cshtml:
<p>Hello World!</p>
要扩展更清晰的依赖点,您可以通过使用ModelBinder 绑定您的预期类型使其更加清晰。然后,您的依赖关系将更加隐蔽,您可以将 ViewBag 的使用替换为直接绑定的 json。
有关ModelBinder 是什么以及它是如何工作的更多信息,我建议您阅读this post。
如果您决定走这条路线,请将第二个 Index 方法和第二个 View 更改为以下内容:
Controllers/ExampleController.cs:
[HttpPost]
public ActionResult Index (HttpPostedFileBase file, string selectedOrgName, string selectedCatName)
{
//...
//let's pass the json directly to the View and make the dependency 100% clear
var json = "some json string";
return View("View2", json);
}
视图/示例/View2.cshtml:
@model System.String
<!-- in the above line, we are telling the view what type we expect to be bound by the controller -->
<h1>View 2</h1>
<!-- specific content here -->
<!-- now include shared content -->
@Html.Partial("SharedContent")
<script>
var ogmap = @Html.Raw(model);
$(function() {
//functionality here
});
</script>