javascript - 重载返回View的Controller时,如何根据ViewBag属性加载不同的内容?

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

我有 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/

相关文章:

asp.net - 开发与生产 : Connection Strings

javascript - Parse.com JS 可以作为 Chrome 扩展使用吗

javascript - 在 OPTIONS 响应后使获取 API 与 CORS 一起工作

javascript - 为什么在删除项目时 Javascript 中的数组不调整大小?

javascript - 将事件指令添加到 svelte html 表达式中?

c# - sql异常,缺少参数化查询

C# - 更新 ef .edmx 文件后维护界面

.net - .NET 世界中的前端开发人员 - 我需要知道什么?

c# - 在Excel中显示时间跨度

c# - 没有页面的 ASP.NET IsPostBack