[英]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.