【问题标题】:Exception raised on returning PartialView from mvc4 controller从 mvc 4 控制器返回局部视图时引发异常
【发布时间】:2023-06-19 08:41:02
【问题描述】:

我有一个包含部分视图的 asp.net mvc4 视图。此视图还包含一个提交按钮,用于过滤网格中的一些元素,如下所示:

配置.cshtml

<div id="MyDiv">
    @Html.Partial("../Grids/_CompGrid")
</div>

 @using (Ajax.BeginForm("Search", "Component", ...)
 {
     <input type="submit" name="_search" value="@Resource.CaptionComponentApplyFilter" />
 }

组件控制器.cs

    public PartialViewResult Search()
    {
        // Do some stuff

        return PartialView("_CompGrid");
    }

当返回上面的局部视图时表明它崩溃了。似乎它没有处理部分视图的正确路径。请参阅以下消息错误:

The partial view '_CompGrid' was not found or no view engine supports the searched locations.
The following locations were searched:
~/Views/Component/_CompGrid.aspx
~/Views/Component/_CompGrid.ascx
~/Views/Shared/_CompGrid.aspx
~/Views/Shared/_CompGrid.ascx
~/Views/Component/_CompGrid.cshtml
~/Views/Component/_CompGrid.vbhtml
~/Views/Shared/_CompGrid.cshtml
~/Views/Shared/_CompGrid.vbhtml

上述文件的目录结构概述如下所示。

/root
  |
  |__ Controllers
  |       |
  |       |__ ComponentController.cs
  |
  |__ Views
  |       |
  |       |__ Home
  |       |     | 
  |       |     |__ Configure.cshtml
  |       |
  |       |__ Grids
  |       |     |
  |       |     |__ _CompGrid.cshtml
  |       |
  |       |  

关于如何解决这个问题的任何想法?

解决方案:

在函数中替换下面的返回行:

    public PartialViewResult Search()
    {
        // Do some stuff

        return PartialView("_CompGrid");
    }

作者:

return PartialView("../Grids/_CompGrid");

但无论如何,如果有人有更好的想法,那将是受欢迎的。

【问题讨论】:

  • 看来我刚刚通过将返回行替换为:return PartialView("../Grids/_CompGrid");但如果有人有更好的想法,请提出建议。

标签: asp.net-mvc asp.net-mvc-4 asp.net-mvc-partialview


【解决方案1】:

你真的有两个选择。首先,您可以使用~/Views/Shared/_CompGrid.cshtml 简单地引用部分。这将始终从 Views 文件夹的根目录开始工作,因此如果您的文件夹结构发生更改,如何修复它会更加明显。

您的另一个选择是将部分放入 ~/Views/Shared/ 文件夹,因为它是 MVC 尝试查找视图时的默认搜索位置之一。 (您实际上可以从上面提供的错误中看到这一点。)因此,假设您将 _CompGrid.cshtml 移动到位于 ~/Views/Shared/_CompGrid.cshtml,以下代码将正确定位您的视图:

组件控制器:

public PartialViewResult Search()
{
    // Do some stuff

    return PartialView("_CompGrid");
}

配置.cshtml:

<div id="MyDiv">
    @Html.Partial("_CompGrid")
</div>

【讨论】:

  • 进一步说明,与Html.Partial 相比,Html.RenderPartial 在性能方面更好。 Html.RenderActionHtml.Action 也是如此。详情请见here
  • 非常感谢您对 RenderPartial 和 RenderAction 的评论:太棒了!我想提一下 Html.RenderPartial 的语法必须介于 {} 和使用分号之间,例如,在我的例子中:@{Html.RenderPartial("../Grids/_CompGrid");} 见下文:*.com/questions/6980823/… 以及它们之间的差异,请参见此处:*.com/questions/2729815/…
  • 您的第一个解决方案不起作用:我已将 return ('../Grids/_CompGrid') 替换为 return ('~Views/Grids/_CompGrid') 并引发以下错误:+ [System .InvalidOperationException] {"未找到局部视图 '~Views/Grids/_CompGrid' 或没有视图引擎支持搜索的位置。搜索了以下位置:\r\n~Views/Grids/_CompGrid"} System.InvalidOperationException –
  • @user1624552 抱歉,我忘记了使用~ 时必须包含.cshtml.。另外,我也错过了第一个/。更新以更正这些。