简体   繁体   English

从其他控制器渲染局部视图

[英]Render Partial View from other controller

Is there a way to render inside my view of controller A a partial view from other controller B ? 有没有办法在我的控制器A视图中呈现来自其他控制器B的局部视图?

Edit: I wrote a partial view that is good for only two controllers and I don't want to copy it to their both Views folder. 编辑:我写了一个仅适用于两个控制器的局部视图,我不想将它复制到两个Views文件夹中。
I want The partial view to be displayed each time the View is rendered not after something happens. 我希望每次呈现视图时都不会显示部分视图。

  1. You can share views between controllers by putting them into the Views/Shared folder. 您可以通过将控制器放入Views / Shared文件夹来共享控制器之间的视图。 Each controller can then render that view by name. 然后,每个控制器都可以按名称呈现该视图。
  2. You can render a partial view (which can be shared between controllers as in (1)) within the current view using Html.Partial() . 您可以使用Html.Partial()在当前视图中渲染局部视图(可以在控制器之间共享,如(1)中Html.Partial()
  3. You can use Html.Action() to invoke an action on a different controller and render the results within the current view. 您可以使用Html.Action()在不同的控制器上调用操作,并在当前视图中呈现结果。
  4. You can use AJAX to load a partial view from a different controller after the page has been rendered. 在呈现页面后,您可以使用AJAX从其他控制器加载局部视图。
@Html.Partial("~/Views/ControllerB/Index.cshtml")

Yes, 是,

return PartialView("/path/view.cshtml");

You just need to work out the path part. 你只需要计算出路径部分。

Alternatively you can put the partial view in views/shared then just return : 或者,您可以将部分视图放在views / shared中,然后返回:

return PartialView("view.cshtml");
@model YourModelNamesapce.ModelName
@{
    ViewBag.Title = "Edit";
    Layout = "~/Views/Shared/_LayoutForPartialViews.cshtml";
}
<table>
    <tr>
       <td>
          @Html.LabelFor(model => model.fieldname)
       </td>
       <td>
          @Html.DisplayFor(model => model.fieldname)
       </td>
    </tr>
    <tr>
       <td>@Html.Action("PartialViewAction", "Controller", new { id = Model.id })</td>
    </tr>
</table>

Just a side note as i found this thread searching for the same question but the answers weren't working: in Orchard CMS modules you cannot use the neat solution posted by Pittfall, you have to use relative paths to return partial views. 只是旁注,因为我发现这个线程搜索相同的问题,但答案不起作用:在Orchard CMS模块中,你不能使用Pittfall发布的整洁解决方案 ,你必须使用相对路径来返回部分视图。 Lets say you have a controller 假设你有一个控制器

Controllers/SiteController.cs

and you want to return the partial view 并且您想要返回局部视图

Shared/MessageList/Items

then in your action methods you need to write 然后在你需要写的动作方法中

return PartialView("../Shared/MessageList/Items");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM