MVC route not working

Update:

As someone remarked, I didnโ€™t have the registration of my route. 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 is currently happening:

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

How to set up routes for this?

I installed the following routes in the 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); } } 
+4
source share
2 answers

Since you have defined default values โ€‹โ€‹for id and productName , the routing mechanism just populates them for you when they are missing, so your / products request gets these default values โ€‹โ€‹and goes to the action of the part.

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

change

Think about whether the {action} parameter is there. Since you have a default action and there is no way to override it, you can still redirect to the details.

+2
source

Route ad missing "s"

action = "Detail s "

Or you can exceed "s" in the name of your action:

public ActionResult Detail s (int? id, string productName)

You decide which one to fix;)

Update: to update the route, simply use:

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

Therefore, when you enter / products, the "Default" route is used.

+3
source

All Articles