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?

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

4 Comments

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??
And why is @Html.RenderPartial(string viewName) for ..? It always gives an error saying Cannot implicitly convert type 'void' to 'object'.
@shashwat - use RenderPartial inside brackets to avoid that error.
e.g. @{ Html.RenderPartial("_ContactForm", Model); }
3
<%= Html.Partial("PartialName", Model) %>

3 Comments

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)
@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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.