当前位置 : 主页 > 网络编程 > ASP >

asp.net-mvc – MVC – 无法解析视图(单独项目中的控制器和视图)

来源:互联网 收集:自由互联 发布时间:2021-06-24
我有一个包含4个项目的解决方案: AS.Core.Common(参考:数据,Web) AS.Core.Controllers(参考:Common,Data,Web) AS.Core.Data AS.Core.Web(参考:数据) 在我的控制器中,我返回视图的任何地方: return View(“
我有一个包含4个项目的解决方案:

> AS.Core.Common(参考:数据,Web)
> AS.Core.Controllers(参考:Common,Data,Web)
> AS.Core.Data
> AS.Core.Web(参考:数据)

在我的控制器中,我返回视图的任何地方:

return View(“~/Views/Home/Index.cshtml”);

它以红色突出显示,我得到一个“无法解析视图’〜/ 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

如何让我的控制器查看我的视图以便他们正确解决?我假设这就是我得到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中,您可以在相应控制器的视图文件夹中返回有效的视图.例如,如果你有一个名为Product的控制器,你可以在路径〜/ Views / Product / Index.cshtml中找到一个文件夹.在Index操作中,您只需使用Controller类基础的View()方法返回一个视图,该方法将保留asp.net mvc中的所有控制器.样品:

public ActionResult Index()
{
   return View();
}

在这种情况下,Asp.Net将在与Action,Index相同名称的文件夹上找到一个View.

您还可以使用View方法返回另一个View,因为您在文件夹上有相应的View,以获取示例:

public ActionResult Index()
{
   return View("About");
}

考虑到这种情况,您应该在Product文件夹中有一个名为About的View.样本:〜/ Views / Product / About.cshtml.

如果将控制器更改为另一个项目(类库),则必须在asp.net mvc初始化上设置控制器的默认命名空间,在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

网友评论