asp.net-mvc - MVC 路由不起作用

标签 asp.net-mvc asp.net-mvc-routing

更新:

正如有人指出的那样,我在路线注册中缺少了 s。现在我有一个次要问题。

这就是我希望它工作的方式:

http://localhost/products/ --> ProductsController.Index()

http://localhost/products/3/apples --> ProductsController.Details(int?id, string ProductName)

这就是当前发生的情况:

http://localhost/products转到我的“详细信息”操作。

如何为此设置路由?

我在 Global.asx 文件中设置了以下路由:

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

    routes.MapRoute(
        "ViewProduct",
        "products/{id}/{productName}",
        new { controller = "Products", action = "Details", id = 0, productName = "" } // Parameter defaults
    );

    routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
    );
}

我有以下 Controller :

public class ProductsController : Controller
{
    //
    // GET: /Products/

    public ActionResult Index()
    {
        IList<Product> products = new List<Product>
        {
            new Product { Id = 57349, ProductName = "Apple" },
            new Product { Id = 57350, ProductName = "Banana" }
        };

        return View(products);
    }

    public ActionResult Details(int? id, string productName)
    {
        Product p = new Product { Id = id.Value, ProductName = productName };

        return View(p);
    }
}

最佳答案

您的路线声明中缺少“s”

action =“详细信息s

或者您的操作名称中多了一个“s”:

公共(public)ActionResult详细信息s(int?id,字符串productName)

由您决定纠正哪一个;)

更新:对于路线更新只需使用:

routes.MapRoute(
    "ViewProduct",
    "products/{id}/{productName}",
    new { 
        controller = "Products", 
        action = "Details" }
);

因此,当您输入/products 时,将使用“默认”路由。

关于asp.net-mvc - MVC 路由不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3462155/

相关文章:

asp.net-mvc - MVC - 应用程序根目录在使用 Url.Content/Url.Action 的 url 中出现两次

c# - HTTP 错误 403.14 - 禁止访问 - 带 IIS Express 的 MVC 4

c# - 根据输入框获取不同的url

asp.net-mvc - 我可以避免这种永久重定向来修复或添加 slug 吗?

c# - 如何忽略服务器端的 EntityValidationErrors

javascript - 使用 Javascript 获取 MVC 表单数据

ASP.NET MVC : How-to inform Model/View about changes in the repository?

jquery - asp.net mvc 所见即所得编辑器/数据库图像上传/预览

c# - 路由和 url 中的 ASP.NET MVC 5 文化

javascript - 加载新页面时如何在 MVC 4 中设置滚动位置