![](/img/trans.png)
[英]How do I pass a partial view with a specific model if another partial view is using a different model?
[英]How do I pass a model property to a partial view with a different model?
给定一个视图模型类
public class Foo
{
public string Fuzz { get; set; }
public Bar Bar { get; set; }
}
public class Bar
{
public string Fizz { get; set; }
}
在控制器动作中,我将以下模型传递给视图:
View(new Foo { Fuzz = "Fizz", Bar = new Bar{ Fizz = "Fuzz" } });
在视图Foo.cshtml中
@model Foo
@Model.Fuzz
@{ Html.RenderPartial("BarPartial", Model.Bar); }
在视图中,局部BarPartial.cshtml
@model Bar
@Model.Fizz
引发错误:
传递到词典中的模型项的类型为Foo,但是此词典需要Bar类型的模型项。
如何将父模型的属性传递给具有该属性类型的模型的局部视图?
public ActionResult test2()
{
return View(new Foo { Fuzz = "Fizz", Bar = new Bar { Fizz = "Fuzz" } });
}
我的观点
@model Foo
@Model.Fuzz
@{ Html.RenderPartial("_partial1",Model.Bar); }
我的部分
@model Bar
@Model.Fizz
没有不同的代码,对我来说很棒
对不起,我刚刚发现错误:
似乎在我正在处理的模型的真实项目中,动作代码的后面部分将其设置为null。
将会发生此错误:
The model item passed into the dictionary is of type Foo but this dictionary requires a model item of type Bar.
如果
View(new Foo { Fuzz = "Fizz", Bar = null });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.