我有以下内容:
Html.RenderPartial("~/bin/Views/SharedViews/_PartialView.cshtml", model.SharedViewModel);
此局部视图来自我已设置为参考的另一个项目;该部分视图设置为“复制到输出目录”,因为MVC不允许您引用Web项目外部的部分视图。我利用了一个可重用的MVC组件,因此将这个视图从一个项目复制到主项目的bin目录中:
Project.Common
> Helpers
>> _PartialView.cshtml (Copy to Output Directory = true)
Project.FirstProject
> References
>> Project.Common
> bin
>> (copied) _PartialView.cshtml
我在bin文件夹中看到该文件; MVC渲染引擎也正在定位它。我已经通过更改路径并观察到与找不到视图有关的错误来验证这一点。所以-MVC找到了视图,但是抛出了这个错误:
_PartialView.cshtml(1):错误CS0103:名称“模型”在当前上下文中不存在
_PartialView.cshtml
的内容:
@model Common.ViewModel
@if (Model.Check)
{
<p>success!</p>
}
如果我将内容修改为仅HTML:
<p>test</p>
我得到同样的错误。如果然后我将调用修改为使用Html.Partial
而不是RenderPartial
,则会收到相同的错误。
这是怎么回事?
如果我随后从调用中删除视图模型,则会得到:
“〜/ bin / Views / _PartialView.cshtml”中的视图必须源自 WebViewPage或WebViewPage。”
同时使用RenderPartial
和Partial
。
在局部视图的顶部添加@inherits System.Web.Mvc.WebViewPage
可以获取html呈现,但不能解决cshtml The name model does not exist
的错误。
更新View Engine以包括bin文件夹并在未指定完整路径的情况下引用视图是行不通的-即使实现以下操作,视图引擎也无法找到视图:
public class CommonAccessibleViewEngine : RazorViewEngine
{
public CommonAccessibleViewEngine()
{
// added to leverage reusable pagination component (and other reusable view components)
// MVC by default doesn't allow you to reference Views outside of your immediate project. By setting views to copy to output directory and then modifying the engine as follows,
// we're telling the view engine to expand its scope to include these referenced views in addition to its default scope.
var newFormats = new string[2] { "~/bin/Views/YourFolder/{0}.cshtml", "~/Views/Shared/{0}.cshtml" };
this.PartialViewLocationFormats = newFormats;
this.ViewLocationFormats = newFormats;
}
}
在Application_Start中使用它:
ViewEngines.Engines.Add(new CommonAccessibleViewEngine());
链接视图也不起作用:
Linked Partial View Not Found By MVC
解决方法:
@inherits System.Web.Mvc.WebViewPage
-这使您可以引用ViewBag
。 Model
仍然无法访问。bin
对我来说)ViewBag.PartialViewModel = partialViewModel;
@{ var Model = (Common.ViewModel)ViewBag.PartialViewModel; }
答案 0 :(得分:0)
我认为这是因为您正在将CSHTML复制到输出目录。如果您关闭“复制到输出目录”,则部分视图的路径将变为:
~/Views/Shared/_PartialView.cshtml
或者无论实际路径是什么。
对于Html.Partial("View")
,视图需要位于Shared文件夹中,或者位于执行控制器的文件夹中,视图引擎才能找到它。您只需定义视图名称即可,而无需文件扩展名。
编辑 您还可以使用“添加为链接”选项将项目链接到指定目录中的Web项目:https://blogs.msdn.microsoft.com/zainnab/2010/11/12/linked-items-in-projects/