我有一个包含 4 个项目的解决方案:
AS.Core.Common
(引用:数据、网络)AS.Core.Controllers
(引用:Common、Data、Web)AS.Core.Data
AS.Core.Web
(引用:数据)在我的 Controller 中,我返回 View 的任何地方:
return View("~/Views/Home/Index.cshtml");
它以红色突出显示,我得到一个
"Cannot resolve view '~/Views/Home/Index.cshtml'"
.所有四个项目都成功构建,但是当我点击 F5 时,我得到以下信息:
Server Error in '/' Application.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.17929
如何让我的 Controller 看到我的 View ,以便它们正确解析?我假设这就是我收到 404 响应的原因。
我的
Global.asax.cs
看起来像这样:public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
// Register the default hubs route: ~/signalr
RouteTable.Routes.MapHubs();
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
我的
RouteConfig.cs
(我添加了命名空间,但似乎没有帮助)public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
namespaces: new[] { "AS.Core.Controllers" },
defaults: new
{
controller = "Home",
action = "Index",
id = UrlParameter.Optional
});
}
这是我的
HomeController.cs
public class HomeController : Controller
{
public ActionResult Index()
{
//return View("~/Views/Home/Index.cshtml");
return View();
}
}
最佳答案
在 asp.net-mvc您可以在相应 Controller 的 View 文件夹中返回一个有效的 View 。例如,如果您有一个名为 Product 的 Controller ,您可以在路径 ~/Views/Product/Index.cshtml
中拥有一个文件夹。 .在您的 Index
操作,您只需使用 View()
返回一个 View Controller
的方法asp.net mvc 中的所有 Controller 都应该继承的类库。 sample :
public ActionResult Index()
{
return View();
}
Asp.Net 将在文件夹中找到一个与您的操作名称相同的 View ,
Index
在这种情况下。您也可以使用
View
返回另一个 View 。方法,因为您在文件夹上有相应的 View ,例如:public ActionResult Index()
{
return View("About");
}
考虑到这种情况,您应该有一个名为
About
的 View 。在 Product
文件夹。 sample :~/Views/Product/About.cshtml
.如果您将 Controller 更改为另一个项目(类库),则必须在 asp.net mvc 初始化时设置 Controller 的默认命名空间,在
Global.asax
上尝试类似的操作。文件和 Application_Start
方法:ControllerBuilder.Current.DefaultNamespaces.Add("NamespaceOfYourProject.Controllers");
看看这篇文章:http://dotnetslackers.com/articles/aspnet/storing-asp-net-mvc-controllers-views-in-separate-assemblies.aspx
关于asp.net-mvc - MVC - 无法解析 View (不同项目中的 Controller 和 View ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16941547/