【问题标题】:How do I pass a model property to a partial view with a different model?如何将模型属性传递给具有不同模型的局部视图?
【发布时间】:2014-06-24 06:40:27
【问题描述】:

给定一个视图模型类

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 类型的模型项。

如何将父模型的属性传递给具有该属性类型的模型的局部视图?

【问题讨论】:

  • 它应该完全按照您在此处显示的那样工作。你确定你在你的“真实代码”中是那样做的吗?
  • 提示:除了@{ Html.RenderPartial("BarPartial", Model.Bar); },你也可以使用更短的@Html.Partial("BarPartial", Model.Bar)
  • 感谢 chrfin,它实际上适用于一个新的 MVC5 项目。但是我收到此错误的其他项目一定有问题。
  • 我试试这个,但你的代码对我来说很好。

标签: c# asp.net-mvc razor model-view-controller renderpartial


【解决方案1】:
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

没有不同的代码,对我来说很好用

【讨论】:

    【解决方案2】:

    对不起,我刚刚发现了错误:

    在我正在处理的实际项目中,我传递的模型似乎在动作代码的后面部分被设置为 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 });
    

    【讨论】:

      猜你喜欢
      • 2014-06-28
      • 1970-01-01
      • 2014-02-05
      • 1970-01-01
      • 2019-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多