【问题标题】:When overloading a Controller that returns a View, how should I load different content based on a ViewBag property?重载返回 View 的 Controller 时,我应该如何根据 ViewBag 属性加载不同的内容?
【发布时间】:2015-05-22 16:43:07
【问题描述】:

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

但这似乎是一种非常糟糕的形式。有更好的方法吗?

【问题讨论】:

  • 为什么不直接使用不同的视图呢?您可以使用部分代码,以便您的代码是 DRY。
  • 在我看来,您可能真正想做的只是简单地发出一个 ajax 请求,然后从第二个索引函数返回 orgcatJSON?
  • @MarkRucker 不能使用 AJAX,因为这是一种上传文件的方法
  • 啊!我现在看到了。好决定。然后我们做一些类似于 Carrie 下面建议的事情,只是我们将 JavaScript 放入部分中。

标签: javascript c# asp.net asp.net-mvc razor


【解决方案1】:

如果您想根据方法在视图中包含不同的内容,那么就这样做并使用两个视图。然后,您可以将部分用于相关内容以保留 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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-02
    • 2015-08-17
    • 1970-01-01
    • 2013-04-17
    • 1970-01-01
    • 2014-02-23
    • 1970-01-01
    相关资源
    最近更新 更多