所以我有這個觀點,它是由CMS生成的。視圖的大腦在RenderAction呈現的另一個視圖中。視圖模型中的嵌套對象會混淆MVC 4路由嗎?
直到現在它已經是這樣的:
Main.cshtml
<div>CMS content</div>
@{
var myContent = new MainContentModel() {
SomethingUsedFurtherDown = "Easier for CMS people to edit"
}
Html.RenderAction("_Main", "Foo", new { arg1 = "this", arg2 = "that", content = myContent });
}
MainContentModel.cs
namespace MyApp.Services.ViewModels.Foo
{
public class MainContentModel
{
public string SomethingUsedFurtherDown { get; set; }
}
}
MainViewModel.cs
namespace MyApp.Services.ViewModels.Foo
{
public class MainViewModel
{
public string Arg1 { set; set; }
public string Arg2 { set; set; }
public string Name { get; set; }
public string Age { get; set; }
public string Address { get; set; }
public MainContentModel Content { get; set; }
}
}
_Main.cshtml
@model MyApp.Services.ViewModels.Foo.MainViewModel
@Html.EditorFor(m => m.Name)
@Html.EditorFor(m => m.Age)
@Html.EditorFor(m => m.Address)
<!-- whatever - doesn't matter -->
FooController.cs
namespace My.App.Controllers
{
using System;
using System.Web.Mvc;
public class FooController
{
public ActionResult Main(string arg1, string arg2, MainContentModel cm)
{
var vm = new MainViewModel() { Arg1 = arg1, Arg2 = arg2, Content = cm };
return this.View("_Main", vm);
}
}
}
一切工作正常。那麼我爲什麼打擾你?那麼,這顯然不是真正的代碼。控制器方法有更多的參數,它們都變得相當混亂。所以我想我會從外部視圖傳入視圖模型。
Main.cshtml
<div>CMS content</div>
@{
var myVM = new MainViewModel() {
Arg1 = "this"
, Arg2 = "that"
, Content = new MainContentModel() {
SomethingUsedFurtherDown = "Easier for CMS people to edit"
}
};
Html.RenderAction("_Main", "Foo", new { vm = myVM });
}
...,只是有一個參數傳遞給控制器的方法
FooController.cs
namespace My.App.Controllers
{
using System;
using System.Web.Mvc;
public class FooController
{
public ActionResult Main(MainViewModel vm)
{
return this.View("_Main", vm);
}
}
}
這就是麻煩開始的地方。我得到這個錯誤:
The view '_Main' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Foo/_Main.aspx
~/Views/Foo/_Main.ascx
~/Views/Shared/_Main.aspx
~/Views/Shared/_Main.ascx
~/Views/Foo/_Main.cshtml
~/Views/Foo/_Main.vbhtml
~/Views/Shared/_Main.cshtml
~/Views/Shared/_Main.vbhtml
~/Views/CMS/_Main.cshtml
~/Views/CMS/Foo/_Main.cshtml
但是,如果我刪除內容模型的初始化,它都會再次運行。好吧,好吧,工作工作。但是錯誤消失了,讓我想出了將內容模型添加到參數列表並將其分配給控制器方法中的視圖模型的明顯解決方案。
Main.cshtml
<div>CMS content</div>
@{
var myVM = new MainViewModel() {
Arg1 = "this"
, Arg2 = "that"
};
var myCm = new MainContentModel() {
SomethingUsedFurtherDown = "Easier for CMS people to edit"
};
Html.RenderAction("_Main", "Foo", new { vm = myVM, cm = myCm });
}
FooController.cs
namespace My.App.Controllers
{
using System;
using System.Web.Mvc;
public class FooController
{
public ActionResult Main(MainViewModel vm, MainContentModel cm)
{
vm.Content = cm;
return this.View("_Main", vm);
}
}
}
除了有相當的現實視圖模型的幾個子對象,我不這很好希望將這些分離出來作爲論據 - 它打破了本來應該是一個整理練習的目的。
問題
是MVC4應該是結合子對象無縫,這是一個錯誤?或者它不是以這種方式工作,我唯一的選擇是將它們分離成上述的額外參數?
乾杯, .pd。