简体   繁体   English

Asp.Net MVC 5使用其他模型调用PartialView

[英]Asp.Net MVC 5 calling PartialView with a different Model

I want to call a PartialView from my Index.cshtml which uses different Model that I want to call PartialView. 我想从我的Index.cshtml调用PartialView,它使用了我想调用PartialView的不同模型。

My Index.cshtml 我的Index.cshtml

@model IEnumerable<myappname.Models.Post>
...
@Html.Partial("_Block")

_Block.cshtml _Block.cshtml

@model myappname.Models.RightBlock
<img src="@Model.blockContent" width="330" />

Controller.cs Controller.cs

...
public PartialViewResult _Block()
    {
        int id = 2;
        RightBlock rb0 = db.RightBlocks.Find(id);

        return PartialView(rb0);
    }
...

Please ignore the id because I just want to call it statically, not dynamically. 请忽略ID,因为我只想静态调用它,而不是动态调用它。 When I run the Index Page, I get an error: 运行索引页时,出现错误:

The model item passed into the dictionary is of type 'System.Data.Entity.Infrastructure.DbQuery`1[myappname.Models.Post]', but this dictionary requires a model item of type 'myappname.Models.RightBlock'. 传递到字典中的模型项的类型为'System.Data.Entity.Infrastructure.DbQuery`1 [myappname.Models.Post]',但是此字典需要类型为'myappname.Models.RightBlock'的模型项。

How can I pass different model to call PartialView? 如何传递不同的模型来调用PartialView? Thank you. 谢谢。

Use Html.Action 使用Html.Action

Index.cshtml Index.cshtml

@Html.Action("Block")

Controller.cs Controller.cs

public ActionResult Block()
{
   // Your code
   return PartialView("_Block.cshtml");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM