开发者

MVC Route not working

Update:

As someone pointed out I was missing an s in my Route registration. Now I have a secondary problem.

This is how I want it to work:

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

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

This is what currently happens:

http://localhost/products goes to my Details action.

How do I set up the routes for this?

I set up the follow开发者_开发百科ing routes in my Global.asx file:

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
    );
}

I have the following 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);
    }
}


You're missing a "s" in your route declaration

action = "Details"

Or have one exceeding "s" in your action name :

public ActionResult Details(int? id, string productName)

It's up to you to decide which one to correct ;)

Update : for the route update just use :

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

So when you type /products the "Default" route gets used.


Because you have defined default values for id and productName the routing engine just fills those in for you when they are missing, so your request to /products is getting those defaults inserted and going to the details action.

Take out: id = 0, productName = "" and you'll get the expected behavior.

edit

Consider having an {action} parameter in there. Since you have a default action and no way to override it you may have everything routed to details anyway.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜