我有 2 个 Index
函数,
public ActionResult Index ( )
{
...
}
和
[HttpPost]
public ActionResult Index (HttpPostedFileBase file, string selectedOrgName, string selectedCatName)
{
...
}
第二种方法添加一个特定的对象:
ViewBag.orgcatJSON = PD.mapOrgs2Cats();
到 ViewBag
,而第一种方法没有。如果我调用了第二种方法,我需要使用 Javascript 对该对象做一些事情;如果我调用了第一种方法,我就不会。所以我正在做的是
var ogmap = @Html.Raw(@ViewBag.orgcatJSON);
$(function() {
if (ogmap != undefined)
{
// do something
}
});
但这看起来很糟糕。有更好的方法吗?
最佳答案
如果您希望根据方法在 View 中显示不同的内容,那么就这样做并使用两个 View 。然后,您可以对相关内容使用 partials 来保留内容 DRY .
像这样分离 View 的一个主要优点是您使依赖项(在本例中为 ViewBag
变量)更加清晰。在您的示例中,您将不得不一直深入到 javascript 中以发现可能需要一些时间的细节。根据经验,我总是尽量让自己的观点保持愚蠢(即完成任务所需的逻辑尽可能少)。
例如:
Controller /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");
}
Views/Example/View1.cshtml:
<h1>View 1</h1>
<!-- specific content here -->
<!-- now include shared content -->
@Html.Partial("SharedContent")
Views/Example/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>
Views/Example/SharedContent.cshtml:
<p>Hello World!</p>
为了扩展更清晰的依赖点,您可以通过使用 ModelBinder
绑定(bind)您期望的类型来使其更清晰。这样你的依赖关系就会隐藏得更少,你可以用你直接绑定(bind)的 json 替换你对 ViewBag
的使用。
有关 ModelBinder
是什么以及它如何工作的更多信息,我建议您阅读 this post .
如果您决定走这条路,请将第二个 Index 方法和第二个 View 更改为以下内容:
Controller /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);
}
Views/Example/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>
关于javascript - 重载返回View的Controller时,如何根据ViewBag属性加载不同的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30401914/