【问题标题】:ASP.NET View Not Found找不到 ASP.NET 视图
【发布时间】:2016-07-30 16:01:22
【问题描述】:

我在 Visual Studio 中创建了一个 Web API 项目。我正在使用属性路由。这是Controllers文件夹下的控制器:

public class RegistrationController : Controller
{
    // GET: Registration
    [Route("")]
    public ActionResult CreateUser(string platform)
    {

         return View("~/Views/Registration/CreateUser.cshtml", platform);
    }
}

当我通过 URL http://localhost/application 调用 CreateUser 操作时,它可以工作,但是当我尝试通过 URL http://localhost/application?platform=android 传递查询字符串参数时,它会给出以下错误:

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

~/Views/Registration/CreateUser.cshtml

~/Views/Registration/android.master

~/Views/Shared/android.master

~/Views/Registration/android.cshtml

~/Views/Registration/android.vbhtml

~/Views/Shared/android.cshtml

~/Views/Shared/android.vbhtml

我无法理解为什么它无法找到存在的视图,或者为什么它甚至尝试使用查询字符串参数的名称来查找视图。

【问题讨论】:

  • 这段代码应该可以正常工作。您确定视图文件包含在项目/解决方案中吗?
  • 您不应该在返回视图中需要视图的整个路径。另外,为什么顶部有一个空的路由装饰器?
  • 虽然不需要整个路径,但它不会破坏任何东西。它应该仍然有效。空路由是让这个动作成为默认。
  • 是的,视图文件包含在项目中。正如我所提到的,当我不使用查询字符串时,它工作得很好。查询字符串不为空时会出现问题。

标签: c# asp.net asp.net-mvc asp.net-web-api razor


【解决方案1】:

它可能可以找到视图。这是它找不到的母版页。

那是因为你使用的是

class Controller : ... {
    ViewResult View(string viewName, string masterName);
}

重载方法,其中

使用 视图名称 创建一个 System.Web.Mvc.ViewResult 对象并 母版页名称,用于呈现响应视图。

线索是它在搜索视图时包含了参数值。因为您传递的平台参数是一个字符串,所以它与使用string viewNamestring masterName 参数的方法调用的方法相匹配。

ControllerViewResult View() 方法有很多过载。在这种情况下,您可能希望将 platform 作为对象模型传递。您可以通过使用命名参数来解决此问题,通过让编译器知道您打算调用哪个重载方法来避免混淆......

public class RegistrationController : Controller {
    // GET: Registration
    [Route("")]
    public ActionResult CreateUser(string platform) {
         return View("~/Views/Registration/CreateUser.cshtml", model: platform);
    }
}

从那里一切都应该按预期工作

【讨论】:

    猜你喜欢
    • 2011-07-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多