0

I want to call a PartialView from my Index.cshtml which uses different Model that I want to call PartialView.

My Index.cshtml

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

_Block.cshtml

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

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. 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'.

How can I pass different model to call PartialView? Thank you.

degergio
  • 81
  • 1
  • 11
  • possible duplicate of [ASP.net MVC4: Using a different model in a partial view?](http://stackoverflow.com/questions/16697942/asp-net-mvc4-using-a-different-model-in-a-partial-view) – Jonathan M Sep 21 '15 at 20:44
  • Easier is you can use ViewBag: @{RightBlock obj = ViewBag.RightBlock as myappname.Models.RightBlock;} – Sandip Bantawa Sep 21 '15 at 21:07
  • It worked when I use: 'Html.Partial("_Block", new myappname.Models.RightBlock())' but when I add 2 more Blocks, Index page works but shows nothing. Source is like that: . No src is defined and rendered. – degergio Sep 21 '15 at 21:15

1 Answers1

1

Use Html.Action

Index.cshtml

@Html.Action("Block")

Controller.cs

public ActionResult Block()
{
   // Your code
   return PartialView("_Block.cshtml");
}
DPac
  • 515
  • 2
  • 8
  • That works! Thank you. Just an edit: return PartialView("_Block") is enough. – degergio Sep 21 '15 at 21:38
  • Yes, if it's under one of the default directories that `WebFormViewEngine` searches for a view, you should only need the name of the view instead of the full path (e.g. "_Partial" instead of "/Dir/_Partial.cshtml"). – DPac Sep 21 '15 at 21:41