How can I render Partial views in asp.net mvc 3?

123,069

Solution 1

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)

Solution 2

<%= Html.Partial("PartialName", Model) %>
Share:
123,069

Related videos on Youtube

peterh
Author by

peterh

Truthful words are not beautiful; beautiful words are not truthful. (Lao Tze) The Last Question

Updated on December 20, 2020

Comments

  • peterh
    peterh over 3 years

    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?

  • Admin
    Admin about 13 years
    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/seach‌​result.cshtml",ViewD‌​ata.Model)
  • David Glenn
    David Glenn about 13 years
    @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.
  • Kasper Holdum
    Kasper Holdum about 13 years
    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.
  • Ishaan Puniani
    Ishaan Puniani about 11 years
    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??
  • shashwat
    shashwat almost 11 years
    And why is @Html.RenderPartial(string viewName) for ..? It always gives an error saying Cannot implicitly convert type 'void' to 'object'.
  • Pradeep
    Pradeep over 10 years
    @shashwat - use RenderPartial inside brackets to avoid that error.
  • Pradeep
    Pradeep over 10 years
    e.g. @{ Html.RenderPartial("_ContactForm", Model); }