簡體   English   中英

如何將模型屬性傳遞給具有其他模型的局部視圖?

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM