我有两种视图模型:
public class ParentViewModel
{
public Id { get; set; }
.....
public ChildViewModel Child{ get; set; }
}
public class ChildViewModel
{
public ChildId { get; set; }
.....
}
控制器:
public ActionResult Index()
{
.... <some code>
return View("NewIndex", ParentViewModel);
}
[HttpPost]
public ActionResult PartialAction(ChildViewModel childView)
{
return RedirectToAction("Index");
}
观点: 索引
@model ParentViewModel
....
@Html.Partial("_Partial", Model.Child)
和_Partial
@model ChildViewModel
... do some stuff with child model
当我尝试打开索引页面时,我遇到了错误:
传递到字典中的模型项是'ParentViewModel'类型,但是这个字典需要一个'ChildViewModel'类型的模型项。
为什么它尝试传递ParentViewModel而不是ChildViewModel。我做错了什么?
答案 0 :(得分:42)
I had the same issue as the OP. From one of the comments, I realized that the second parameter shouldn't be null, i.e from
@model ParentViewModel
@Html.Partial("_Partial", Model.Child)
If Model.Child is null, then Model is passed instead of Model.Child. If there will be cases when the second parameter is null, then you will have to check first in your code and maybe pass an initialized Child as the second parameter. Something like this
@Html.Partial("_Partial", new Child())
答案 1 :(得分:14)
答案是需要将空对象传递给Partial,比如
@Html.Partial("_Partial", new ChildViewModel ())
答案 2 :(得分:0)
您可以从PartialView("...")
返回Controller
,然后从索引视图中调用该操作。
控制器:
public ActionResult Index()
{
.... <some code>
return View("NewIndex", ParentViewModel);
}
public ActionResult Partial(ChildViewModel cvm)
{
var vm = cvm ?? new ChildViewModel(); //if cvm from the parent view is null, return new cvm
return PartialView("_Partial", vm) //return partial view
}
[HttpPost]
public ActionResult PartialAction(ChildViewModel childView)
{
return RedirectToAction("Index");
}
和索引
@model ParentViewModel
....
@Html.Action("Partial", Model.Child)
或者,您可以在Index()
中初始化ParentViewModel
公共ActionResult索引()
{
.... <some code>
return View("NewIndex", new ParentViewModel{Child = new ChildViewModel});
}