繁体   English   中英

当重载一个返回View的Controller时,我该如何根据ViewBag属性加载不同的内容?

[英]When overloading a Controller that returns a View, how should I load different content based on a ViewBag property?

我有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
    }
});

但这似乎是非常糟糕的形式。 有没有更好的方法呢?

如果您希望在视图中使用不同的内容,具体取决于方法,那么请执行此操作并使用两个视图。 然后,您可以使用谐音的相关内容,以使事情

分离这样的视图的一个主要优点是你已经使你的依赖(在这种情况下是一个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>

Views / Example / SharedContent.cshtml

<p>Hello World!</p>

要扩展更清晰的依赖关系点,您可以通过使用ModelBinder绑定您的预期类型来使其更清晰。 然后你的依赖关系会更少隐藏,你可以用直接绑定的json替换你对ViewBag使用。

有关ModelBinder是什么以及它如何工作的更多信息,我建议你阅读这篇文章

如果您决定使用此路线,请将第二个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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM