MVC 3 Route problem - asp.net-mvc

ActionLink result "http://localhost:5089/Article/GetArticlesByCategory?category=ASP.NET&categoryId=2". i want to show that link type "http://localhost:5089/Blog/ASP.NET". what is wrong route named "Article".
Routes:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "index", id = UrlParameter.Optional } // Parameter defaults
);
routes.MapRoute(
"Article",
"Blog/{category}", //
new { controller = "Article", action = "GetArticlesByCategory", category = UrlParameter.Optional, categoryId = UrlParameter.Optional }
Link:
#Html.ActionLink(k.Name, "GetArticlesByCategory", "Article",
new { category = k.Name, categoryId = k.CategoryId }, null)
SOLVED
GetArticlesByCategory parameter int categoryId changed to >> string category and replaced action codes as to new parameter (string category)
Routes replaced with:
routes.MapRoute(
"Category",
"Blog/{category}",
new { controller = "Article", action = "GetArticlesByCategory", category = UrlParameter.Optional }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "index", id = UrlParameter.Optional } // Parameter defaults
);
ActionLink replaced with:
#Html.ActionLink(k.Name, "GetArticlesByCategory", "Article",
new { category = k.Name }, null)

There are a few issues. First, and most important, your routes are specified in the wrong order. The default route should be defined last. Second, never define a route with two optional parameters. It just causes too many problems.
Try the following for your routes:
routes.MapRoute(
"CategoryAndId",
"Blog/{category}/{categoryId}",
new { controller = "Article", action = "GetArticlesByCategory" }
);
routes.MapRoute(
"CategoryOnly",
"Blog/{category}",
new { controller = "Article", action = "GetArticlesByCategory",
category = UrlParameter.Optional }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "index",
id = UrlParameter.Optional } // Parameter defaults
);

You are not specifying the action in the route
routes.MapRoute(
"Article",
"Blog/{action}/{category}/{categoryId}", //
new { controller = "Article", action = "GetArticlesByCategory", category = UrlParameter.Optional, categoryId = UrlParameter.Optional }
I suggest you use Phil Haack's routes debug, http://haacked.com/archive/2008/03/13/url-routing-debugger.aspx. A great way for debugging your MVC routes

If you want the link to show as http://localhost:5089/Blog/ASP.NET, you'll need to change the actionlink as such:
#Html.ActionLink(k.Name, "GetArticlesByCategory", "Article",
new { category = k.Name }, new { #title = "Kategorisindeki Makaleler", #class = "selected" })
Since you don't want the CategoryID in the link, there is no need to put it in. the route isn't being matched by the actionlink because it expects a CategoryID parameter as well
EDIT
If you want the CategoryID to be read from the route, it needs to be added to the route. otherwise it will just be appended as a parameter (like in your original example).
If you change your route to:
"Blog/{categoryId}/{category}"
or
"Blog/{category}/{categoryId}"
The link will now look like Blog/2/ASP.NET or Blog/ASP.NET/2 but if you want the categoryId to be read from the URL, then I don't think you have much choice

Related

MVC: Multiple Routes for 1 Controller

I want users to be able to access the "/Linecard" page of my ASP.Net MVC site using "/Linecard" or "/Manufacturers" as the URL... so same controller, 2 different possible URLs.
I tried adding the following:
routes.MapRoute(
name: "Manufacturers",
url: "Manufacturers/{action}/{id}",
defaults: new { controller = "Linecard", action = "Index", id = UrlParameter.Optional }
);
Adding this after the "Default" route doesn't work at all and I get a 404 error when I go to "/Manufacturers". Putting it BEFORE "Default" works, but then only "/Manufacturers" shows up in the URL when I click menu links since it is the first match. I would like "/Linecard" to always show as the URL.
Any pointers? Is there a certain constraint I can use to accomplish this? Thanks!
I had the same problem when we moved to extension-less URLs. We needed to continue to support one route with extensions. I got around it by having my default route apply to everything except the old URL, then after that mapping one specifically for the exception
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
// if controller specified does not match 'manufacturers' (case insensitive)
new { controller = "^((?i)(?!manufacturers).)*$" },
new string[] { "Namespace.Of.Controllers" }
);
routes.MapRoute(
"Manufacturers", // Route name
"Manufacturers/{action}/{id}", // URL with parameters
new { controller = "Linecard", action = "Index", id = UrlParameter.Optional },
new string[] { "Namespace.Of.Controllers" }
);
You could also set an order when mapping your routes with the defaults at the end like so
routes.MapRoute(
name: "Manufacturers",
url: "Manufacturers/{action}/{id}",
defaults: new { controller = "Linecard", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);

How to choose route in MVC3

I have global.ascx with three routes
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"TestRoute",
"{id}",
new { controller = "Product", action = "Index3", id = UrlParameter.Optional },
new { id = #"\d+" } //one or more digits only, no alphabetical characters
);
routes.MapRoute(
"TestCatalogRoute",
"{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "RsvpForm", id = UrlParameter.Optional } // Parameter defaults
//new { controller = "Product", action = "Index2", id = UrlParameter.Optional } // Parameter defaults
);
}
When I enter url:
http://mydomain.com/
It uses "TestCatalogRoute" route, but I want "Default" route T.T
How to:
with url: http://mydomain.com it uses "Default" route
with url: http://mydomain.com/1 it uses "TestRoute" route (It's already done!)
with url: http://mydomain.com/abc it uses "TestCatalogRoute" route
Remove id = UrlParameter.Optional for TestCatalogRoute then
Change the order of your routes. The routehandler will validate each route, first one that matches will get picked. So if you put the second one last, you should be fine?
I can recomend using Routing Debugger to debug your route easy to use.
http://haacked.com/archive/2008/03/13/url-routing-debugger.aspx

ASP.NET MVC3 not right index page because of routes

I have these routes:
routes.MapRoute(
"ActionOnly",
"{action}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new { action = "Klub|Historie" });
routes.MapRoute(
"Administrace", // Route name
"Administrace/{controller}/{action}/{id}", // URL with parameters
new { controller = "Administrace", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
// Hrac/Jmeno_hrace
routes.MapRoute(
"Hrac",
"Hrac/{name}",
new { Controller = "Hrac", Action = "Name" }
);
// pro aktivaci uzivatele který se registroval, ale jeste nepotvrdil email
routes.MapRoute(
"Activate",
"Account/Activate/{username}/{key}",
new { controller = "Account", action = "Activate", username = UrlParameter.Optional, key = UrlParameter.Optional }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
Why #Html.ActionLink("Domů", "Index", "Home") is creating website.com/Administrace/Home and not website.com/Home/index and how can I fix it?
Your Administrace route is swallowing all controllers.
You should change it to hard-code the controller name:
routes.MapRoute(
"Administrace", // Route name
"Administrace/Administrace/{action}/{id}", // URL with parameters
new { controller = "Administrace", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
If you want that route to work for multiple controllers, you should replace it with an area (or just add a constraint).
Use #Html.RouteLink instead with the route name being default
Link to something that might help:
What's the difference between RouteLink and ActionLink in ASP.NET MVC?

Why doesn't my routing work?

Im trying to set up an alternative route on my application...
routes.MapRoute(
"x", // Route name
"{controller}/{action}/{datetime}", // URL with parameters
new { controller = "Home", action = "Index", datetime = UrlParameter.Optional } // Parameter defaults
);
I have the action...
public ActionResult GetBlogsByMonth(string datetime)
{
if (datetime!= null)
{
IList<BlogModel> blogs = (IList<BlogModel>)manager.GetBlogsInMonth(DateTime.Parse(datetime)).ToList();
return View(blogs);
}
else
{
return View();
}
}
But when I put the debugger on the action the datetime is always null... :-(
Probably, your request has been caught by another route. Make sure to put your route at the top when you are registering them.
For example, if you are using this route with the default one, the default one will catch the request, not your custom route if you reference them in the following order:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
routes.MapRoute(
"x", // Route name
"{controller}/{action}/{datetime}", // URL with parameters
new { controller = "Home", action = "Index", datetime = UrlParameter.Optional } // Parameter defaults
);
As for the solution, as #Darin suggested, you need to define a constraint because if you put your custom one in front, this time the default one will never be hit.
routes.MapRoute(
"x", // Route name
"{controller}/{action}/{datetime}", // URL with parameters
new { controller = "Home", action = "Index", datetime = UrlParameter.Optional }, // Parameter defaults
new { datetime = #"^(19|20)\d\d([- /.])(0[1-9]|1[012])\2(0[1-9]|[12][0-9]|3[01])$" }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
The below URLs will be caught by your custom route:
/Poo/Bar/2011-11-31
/Poo/Bar/2011-01-04
/Poo/Bar/2011-01-04
You can change the RegEx for your needs.
When constructing a link to your action you can use a RouteLink instead of an ActionLink. With the RouteLink you can pass a named route name to force the right route is chosen to construct the link. For your example the link should look somehow like this:
#Html.RouteLink("Blog Posts...", "x", new { controller="Blog", action="GetBlogsByMonth" datetime = THEDATETIME })
Hint: You can use the DateTime type in your action as parameter instead of a String type so you can avoid the unnecessary call to DateTime.Parse

How to handle routing with two actions with the same number of paramaters in MVC3? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
ActionLink to show parameters in URL instead of querystring?
I have the following routes:
routes.MapRoute(
"List", // Route name
"{Home}/{list}/{id}/{name}", // URL with parameters
new {
controller = "Home",
action = "List",
id = UrlParameter.Optional,
name = UrlParameter.Optional } // Parameter defaults
);
routes.MapRoute(
"Details", // Route name
"{Home}/{details}/{id}/{name}", // URL with parameters
new {
controller = "Home",
action = "Details",
id = UrlParameter.Optional,
name = UrlParameter.Optional } // Parameter defaults
);
I am trying for:
/home/list/1/a
/home/details/2/b
The above results in home/details/2?name=b
Assuming you haven't gotten your code example wrong, You can't.
The route handler will pick the 1st route that matches.
However, from what it looks like what you actually want is this:
routes.MapRoute(
"List", // Route name
"home/list/{id}/{name}", // URL with parameters
new {
controller = "Home",
action = "List",
id = UrlParameter.Optional,
name = UrlParameter.Optional } // Parameter defaults
);
routes.MapRoute(
"Details", // Route name
"home/details/{id}/{name}", // URL with parameters
new {
controller = "Home",
action = "Details",
id = UrlParameter.Optional,
name = UrlParameter.Optional } // Parameter defaults
);
In fact, those two are similar enough that it can be distilled into 1 route
routes.MapRoute(
"Details", // Route name
"{controller}/{action}/{id}/{name}", // URL with parameters
new {
controller = "Home",
action = "List",
id = UrlParameter.Optional,
name = UrlParameter.Optional } // Parameter defaults
);
Avoid creating a route with two UrlParameter.Optional declarations.
You can achieve your routing by adding one route above the default route, like so:
routes.MapRoute(
"Id_Name", // Route name
"{controller}/{action}/{id}/{name}", // URL with parameters
new{
controller = "Home",
action = "List" } // Parameter defaults
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new {
controller = "Home",
action = "List",
id = UrlParameter.Optional} // Parameter defaults
);
The first route will create the URL you want for when both variables are declared. The second route will work for either one variable or no variables.

Resources