44

I have some data in ViewData.Model, and in my views I want to write a partial view and to pass their current model I have in my page.

How I can pass their current ViewData.Model and render them through the location of partials?

peterh
  • 11,875
  • 18
  • 85
  • 108

2 Answers2

104

Create your partial view something like:

@model YourModelType
<div>
  <!-- HTML to render your object -->
</div>

Then in your view use:

@Html.Partial("YourPartialViewName", Model)

If you do not want a strongly typed partial view remove the @model YourModelType from the top of the partial view and it will default to a dynamic type.

Update

The default view engine will search for partial views in the same folder as the view calling the partial and then in the ~/Views/Shared folder. If your partial is located in a different folder then you need to use the full path. Note the use of ~/ in the path below.

@Html.Partial("~/Views/Partials/SeachResult.cshtml", Model)
methon.dagger
  • 505
  • 9
  • 28
David Glenn
  • 24,412
  • 19
  • 74
  • 94
  • hi i my case container view is binded with "ContainerModel" and the partial view is in shared folder and is binded with "ChildrenModel" in @Html.Partial("~/Views/Partials/SeachResult.cshtml", Model) it is giving exception that "ChildrenModel is not declared. it may be inaccessible due to its protection level" can you suggest what to do?? – Ishaan Puniani Apr 25 '13 at 14:39
  • 1
    And why is `@Html.RenderPartial(string viewName)` for ..? It always gives an error saying `Cannot implicitly convert type 'void' to 'object'`. – shashwat Aug 13 '13 at 13:24
  • 3
    @shashwat - use RenderPartial inside brackets to avoid that error. – Pradeep Dec 19 '13 at 01:29
  • 3
    e.g. @{ Html.RenderPartial("_ContactForm", Model); } – Pradeep Dec 19 '13 at 01:29
3
<%= Html.Partial("PartialName", Model) %>
Kasper Holdum
  • 12,993
  • 6
  • 45
  • 74
  • it's not worked in MVC 3. if i pass the location of partial in partialname that they not worked and give me error that @Html.RenderPartial(Globals.Theme_Path+"views/partials/seachresult.cshtml",ViewData.Model) –  Mar 26 '11 at 10:17
  • @Moby It looks like the partial view cannot be found, see my answer, but can you post the error message and then we maybe able to help further. – David Glenn Mar 26 '11 at 10:34
  • You shouldn't apply themes by using different views. Themes should be applied by using different images/css files. Also, you should use Partial and not RenderPartial. – Kasper Holdum Mar 26 '11 at 10:39