RenderPartial a view from another controller (and in another folder)

巧了我就是萌 提交于 2019-12-03 09:33:54
Ravinder Singh Bhanwar

this is works for me!

@Html.Partial("~/Views/NewsFeeds/NewsFeedPartial.cshtml")

You can refer to Views with full paths, like:

Html.RenderPartial("~/Views/Definition/DefinitionDetails")

Even better, use the T4MVC library, which does the above and makes it (quasi-) strongly-typed. You can refer to any view from any controller or view. You use it like this:

Html.RenderPartial(MVC.Definition.Views.DefinitionDetails)

or

Html.RenderPartial(MVC.Definition.Views.DefinitionDetails, myModel)

Just to clarify which options work exactly:

1) The extension of the view file is required if you supply a path.

2) If you do not supply a path, do not supply the extension.

The examples below assume cshtml files.

Use RenderPartial in a code block:

// This looks in default view folder, then shared, checking for .aspx, .cshtml etc
Html.RenderPartial("DefinitionDetails"); 

// This looks in specified path and requires the extension
Html.RenderPartial("~/Views/Definition/DefinitionDetails.cshtml");

Use Partial for inline Razor syntax:

// This looks in default view folder, then shared, checking for .aspx, .cshtml etc
@Html.Partial("DefinitionDetails")

// This looks in specified path and requires the extension
@Html.Partial("~/Views/Definition/DefinitionDetails.cshtml")

Note: Apparently RenderPartial is slightly faster than Partial, but I also expect fully pathed names will be a faster than letting MVC search for the file.

If you are producing partials in a loop (i.e. from a collection in your view model), it is likely you will need to pass through specific viewmodels:

e.g.

   @foreach (var group in orderedGroups)
   {
       Html.RenderPartial("~/Views/ControllerName/ViewName.cshtml", group);
   }

I just had to do all this on a project and found the marked answer a little misleading.

Could you not copy the partials into the shared folder then just do:

<% Html.RenderPartial("DefinitionDetails", i); %> and

<% Html.RenderPartial("DefinitionEditActions"); %>

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!