简体   繁体   English

如何使ASP.NET正确路由控制器?

[英]How do I get ASP.NET to route a controller properly?

I have this in my controller: 我的控制器中有这个:

    public ActionResult Details(int? id)
    {
        if(id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }

        Sales saleRecord = new Sales();
        var result = saleRecord.GetSalesOrderHeader((int)id);


        return View(result);
    }

However if I browse to /ControllerName/Details/5 I get this error: 但是,如果我浏览到/ ControllerName / Details / 5,则会出现此错误:

"Server Error in '/' Application. - The view 'details' or its master was not found or no view engine supports the searched locations." ““ /”应用程序中的服务器错误。-未找到视图“详细信息”或其主视图,或者没有视图引擎支持搜索到的位置。”

The strange thing is that if I use ASP.NET Scaffolding to generate a view, the Details part of that works fine. 奇怪的是,如果我使用ASP.NET Scaffolding生成视图,则该视图的Details部分可以正常工作。 It's basically the same code I have above as well. 基本上,我上面也有相同的代码。

Here's my RouteConfig.cs, if that's relevant: 如果相关,这是我的RouteConfig.cs:

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

So why is that the scaffolding controller works fine, without having anything specific added to RouteConfig, yet my controller Details method is not working? 那么,为什么没有在RouteConfig中添加任何特定的东西而使脚手架控制器正常工作,而我的控制器Details方法却无法正常工作呢?

There should be more detail in error that what locations have been searched. 错误的地方应该有更多详细信息,即已搜索了哪些位置。 Did you put break point in controller and checked if its being hit? 您是否将断点放在控制器中并检查是否被击中?

try 尝试

return View((object)result);

instead of 代替

return View(result)

cause its calling overload View(string viewName) 导致其调用重载View(string viewName)

If this doesn't work, try to specify viewName explicitly like this: 如果这不起作用,请尝试像这样显式指定viewName:

return View("ViewName", name);

Additionally, check your folder structure. 此外,检查您的文件夹结构。 MVC looks for views (like Index) under the views folder but they also have to be under a folder named after their controller (except partial views). MVC在views文件夹下查找视图(如Index),但它们也必须位于以其控制器命名的文件夹下(部分视图除外)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM