【问题标题】:Why is Asp.Net MVC not searching for a view in my Shared directory?为什么 Asp.Net MVC 不在我的共享目录中搜索视图?
【发布时间】:2011-10-03 05:03:29
【问题描述】:

在我的/Views/Shared/ 文件夹中,我创建了一个EntityNotFound.cshtml 剃刀视图。在我的一个控制器操作中,我有以下调用:

return View(MVC.Shared.Views.EntityNotFound, "Company");

这会导致以下异常:

System.InvalidOperationException:未找到视图“~/Views/Shared/EntityNotFound.cshtml”或其主视图,或者没有视图引擎支持搜索到的位置。搜索了以下位置:

~/Views/Company/Company.cshtml

~/Views/Company/Company.vbhtml

~/Views/Shared/Company.cshtml

~/Views/Shared/Company.vbhtml

我很困惑,因为它似乎甚至没有尝试搜索~/Views/Shared/EntityNotFound.cshtml。即使我将MVC.Shared.Views.EntityNotFound 替换为"EntityNotFound",我也会遇到同样的错误。

为什么 Asp.Net MVC 甚至没有尝试找到我的共享视图?

【问题讨论】:

    标签: asp.net-mvc views


    【解决方案1】:

    查看View(); 的重载列表

    http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.view.aspx

    具体来说,当您传递View(string,string); 时,它会将第二个字符串视为主视图的名称。

    可能发生的事情是它找不到“公司”主视图,您不会看到异常消息说

    ...或找不到它的主人...

    这意味着它可能正在寻找NotFoundException.cshtml,但无法正确找到它正在寻找的作为主人的Company.cshtml

    【讨论】:

    • 啊,所以有一个字符串模型是个坏主意:)
    • 确实,您可以通过将字符串模型类型转换为对象来欺骗系统...所以View("NotFoundException", (object)"Company");
    【解决方案2】:

    正确的语法应该是这样(不要传递路径,MVC 是约定俗成的语言)

      return View("EntityNotFound");
    

    假设“公司”是您要传递给视图的参数,请尝试如下:

      ViewBag.ErrorEntity = "Company";
      return View("EntityNotFound");
    

    从视图中

      <p>Entity not found: @ViewBag.ErrorEntity</p>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-05
      • 2021-03-10
      • 1970-01-01
      相关资源
      最近更新 更多