I've been writing a blog as a learning project for a while now and I've just rewritten my URL structure in order to improve the organisation of my controllers. This has gone fairly smoothly, but I have a little problem with a conflicting route.
I'm trying to setup my URL structure as follows:
/
/page/2
/category
/category/page/2
The categories are stored within the database. This works fine at the moment, but I just noticed that when I try to link back to the home page that it's hitting /page instead.
Here's my current route table:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Admin",
"admin",
new { controller = "Admin", action = "Index" }
);
routes.MapRoute(
"ShowPagedPostsByCategory",
"{category}/page/{page}",
new { controller = "Posts", action = "Index", page = UrlParameter.Optional },
new { page = #"(\d+)?" }
);
routes.MapRoute(
"ShowPagedPosts",
"page/{page}",
new { controller = "Posts", action = "Index", page = UrlParameter.Optional },
new { page = #"(\d+)?" }
);
routes.MapRoute(
"ShowPostsByCategory",
"{category}",
new { controller = "Posts", action = "Index" }
);
routes.MapRoute(
"ShowTaggedPosts",
"posts/tagged/{tag}",
new { controller = "Posts", action = "ShowTaggedPosts", tag = UrlParameter.Optional }
);
routes.MapRoute(
"EditDeleteComment",
"posts/{action}/{id}",
new { controller = "Posts" },
new { action = #"EditComment|DeleteComment", id = #"\d+" }
);
routes.MapRoute(
"AddComment",
"{controller}/comment",
new { controller = "Posts", action = "Comment" }
);
routes.MapRoute(
"ShowPost",
"{controller}/{PostID}/{*slug}",
new { controller = "Posts", action = "ShowPost", slug = UrlParameter.Optional },
new { PostID = #"\d+" }
);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Posts", action = "Index", id = UrlParameter.Optional }
);
}
I can see what the problem is: the home URL of '/' is matching with the ShowPagedPosts route, but moving that below the default route seems to be the wrong thing to do. That makes me think my approach to this is a bit off. Can anyone point me in the right direction please?
Edit: Actually, with RouteDebugger I can see that it's actually matching the ShowPagedPosts and ShowPostsByCategory routes.
When using Html.ActionLink, the first matching route will be used.
If you want to use another specific route, use Html.RouteLink which takes the route's name as a parameter.
Related
I have an custom mvc route it's not working. if i define the route before home route then it's working otherwise not.
this code is not working.
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
"Citysearch",
"{state}",
new { controller = "Dashboard", action = "GetDynamicContent" }
);
when i define the citysearch first then it's working something like this
routes.MapRoute(
"Citysearch",
"{state}",
new { controller = "Dashboard", action = "GetDynamicContent" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
and another problem is this is the url of city search http://localhost:51381/dynamic-content. dynamic-content this is my state paramter. It's calling of my Dashboard/GetDynamicContent. but problem is when application run after login url is http://localhost:51381/Home it is calling always Dashboard/GetDynamicContent how to get rid of this problem please help me.
Routes are read from top to bottom. Therefore, the first route match will be used when routing.
Try this
routes.MapRoute(
"Home",
"Home/{action}",
new { controller = "Home", action = "index" }
);
routes.MapRoute(
"Citysearch",
"DynamicContent/{state}",
new { controller = "Dashboard", action = "GetDynamicContent" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
You have to use some fix part in your url as shown below DynamicContent/ to solve issue you are facing. And your url should be like http://localhost:51381/DynamicContent/dynamic-content.
routes.MapRoute(
"Citysearch",
"DynamicContent/{state}",
new { controller = "Dashboard", action = "GetDynamicContent" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
I would like to add my experience in this issue "custom-map-route is not working".
Myobservation:custom url routing not working when page is redirected using href="redirected page" . when i am using #Url.Action() for redirection then custom routing started working.
here is my initial code(peice of code)
return '<a href="/Home/AuthorityForm?formid=' + '#ViewBag.formid' + "&SubmittedFormId=" + full.ConsentId + """ + 'target="_blank">ViewForm';
i changed to
var link = '#Url.Action("AuthorityForm", "Home", new { formid = ViewBag.formid, SubmittedFormId = "-1" })';
link = link.replace("-1", full.ConsentId);
return 'ViewForm'
this may help someone..
I have a website (http://jsoncore.net) that I am using to learn .NET Core 2 and I want to remove the shared hosting folder name from the URL that is added to links and sources. For example I add an Html.ActionLink like this:
#Html.ActionLink(page.NavTitle, page.Slug, "Home")
and the system writes it to this:
Blog
I want to remove the "/jsoncore" from the link URL so that it should look like this:
Blog
Here are the routes defined in Startup.cs:
app.UseMvc(routes =>
{
routes.MapRoute(
"AdminController",
"Admin/{action}",
new { controller = "Admin", action = "Index"}
);
routes.MapRoute(
"BlogController-BlogHome",
"Blog/",
new { controller = "Blog", action = "Index" }
);
routes.MapRoute(
"BlogController-Post",
"Post/{id}",
new { controller = "Blog", action = "Post", id = "" }
);
routes.MapRoute(
"BlogController-Post-Tag",
"Blog/Tag/{id}",
new { controller = "Blog", action = "Tag", id = "" }
);
routes.MapRoute(
"BlogController-Post-Category",
"Blog/Category/{id}",
new { controller = "Blog", action = "Category", id = "" }
);
routes.MapRoute(
"HomeController",
"{action}/{id}",
new { controller = "Home", action = "Index", id = "id?" }
);
routes.MapRoute("AccountController", "Login", new { controller = "Account", action = "Login"});
routes.MapRoute("page", "{id}", new { controller = "Home", action = "Page", url = "" });
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
If the site is hosted in a virtual directory /jsoncore/ there's no way to remove that from the URL, as it's actually part of the URL, i.e. you need that to get to the right place. Otherwise, the requests would hit the site hosted at just http://jsoncore.net, which isn't this application. It's called a Universal Resource Locator for a reason. Only the correct URL will work, which includes the /jsoncore/ part, apparently.
Some shared hosting lets you bind to a domain or subdomain (although there'd probably be an upcharge for that). If that's available, that would be your best bet. Then, you can effectively host your site at the root of that domain/subdomain, without needing a path prefix.
I dont understand the RegisterRoutes perfectly. Lets assume the browser's current URL is
//Home/ListCompanies/{filter}
http://localhost:21047/Home/ListProducers/Yerli
we came to the address above with the link below
#Html.ActionLink("Yerli Markalar", "ListProducers/Yerli", "Home")
And I have a link on the current page like below
#Html.ActionLink("Bayiler", "ListCompanies", "Home")
http://localhost:21047/Home/ListCompanies/Yerli
But when I hover on the last link, it displays "Yerli" filter as well which I dont give it in the link
Why does the filter "Yerli" come here? It should seem like below
http://localhost:21047/Home/ListCompanies/
What am I doing wrong?
here are my Routes
routes.MapRoute(
null,
"Home/ListProducers/{filter}", // Route name
new { controller = "Home", action = "ListProducers", filter = UrlParameter.Optional } // Parameter defaults
);
routes.MapRoute(
null,
"Home/ListCompanies/{filter}", // Route name
new { controller = "Home", action = "ListCompanies", filter = UrlParameter.Optional } // Parameter defaults
);
Firstly, you do not use
#Html.ActionLink("Yerli Markalar", "ListProducers/Yerli", "Home")
If "Yerli" is the parameter to be passed to
public ActionResult ListProducers(string filter)
then it needs to be
#Html.ActionLink("Yerli Markalar", "ListProducers", "Home", new { filter = "Yerli" }, null)
which will generate ..../Home/ListCompanies/Yerli
Your problem is that you have generated the action parameter as ListCompanies/Yerli whereas it should be ListCompanies
Note you should also name your routes
routes.MapRoute(
"ListProducers", // name it!
"Home/ListProducers/{filter}", // Route name
new { controller = "Home", action = "ListProducers", filter = UrlParameter.Optional } // Parameter defaults
);
However, those routes seem unnecessary and you could just delete them and let the default route handle it
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
and just change the method to
public ActionResult ListProducers(string id)
and use
#Html.ActionLink("Yerli Markalar", "ListProducers", "Home", new { id = "Yerli" }, null)
which will produce exactly the same result
I'm having a problem trying to get routing to work with ASP.NET MVC 3.0. I have the following routes declared:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "RsvpForm", id = UrlParameter.Optional }
);
routes.MapRoute(
"TestRoute",
"{id}",
new { controller = "Product", action = "Index3", id = UrlParameter.Optional }
);
routes.MapRoute(
"TestRoute2",
"{action}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
When I visit:
http://localhost
The site works correctly, and it appears to hit Default route.
When I visit:
http://localhost/1
I get a 404:
Server Error in '/' Application.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is
temporarily unavailable. Please review the following URL and make
sure that it is spelled correctly.
Requested URL: /1
Here are the actions those routes correspond to:
public ActionResult Index3(int? id)
{
Product myProduct = new Product
{
ProductID = 1,
Name = "Product 1 - Index 3",
Description = "A boat for one person",
Category = "Watersports",
Price = 275M
};
Product myProduct2 = new Product
{
ProductID = 2,
Name = "Product 2 - Index 3",
Description = "A boat for one person",
Category = "Watersports",
Price = 275M
};
ViewBag.ProcessingTime = DateTime.Now.ToShortTimeString();
if (id == 1)
return View("index", myProduct);
else
return View("index", myProduct2);
}
How do I structure my routes so that all three action methods are hit correctly?
ASP.NET MVC Routing evaluates routes from top to bottom. So if two routes match, the first one it hits (the one closer to the 'top' of the RegisterRoutes method) will take precedence over the subsequent one.
With that in mind, you need to do two things to fix your problem:
Your default route should be at the bottom.
Your routes need to have constraints on them if they contain the same number of segments:
What's the difference between:
example.com/1
and
example.com/index
To the parser, they contain the same number of segments, and there's no differentiator, so it's going to hit the first route in the list that matches.
To fix that, you should make sure the routes that use ProductIds take constraints:
routes.MapRoute(
"TestRoute",
"{id}",
new { controller = "Product", action = "Index3", id = UrlParameter.Optional },
new { id = #"\d+" } //one or more digits only, no alphabetical characters
);
There are other issues with your set up, but those are two things that come to mind right off the bat.
Your routes MapRoute Default should be the last.
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "RsvpForm", id = UrlParameter.Optional }
);
Push the most generic route to the last of the MapRoute call chain.
Try this:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"TestRoute",
"{id}",
new { controller = "Product", action = "Index3", 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
);
routes.MapRoute(
"TestRoute2",
"{action}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Move your Default route to the end, Default route should be the last route to define because it acts as a catch all route
In my case, the answer for the same problem was a matter of needing to "include in project" the relevant controllers and views instead of incorrect routing rules.
When mine were created, they weren't automatically included for some reason. This problem was revealed after I closed and re-opened the solution.
{+1 hate} awarded to Visual Studio for its faulty hyper-automation sending me digging through Web.Config files, trying to tack on extensions, and even trying (and failing) to whip up a decent ErrorController.
I'm trying to define a route configuration which will allow an optional 'region' in the following URLs, all of which will default to the home page:
/uk/home // where the 'uk' parameter can be either 'uk' or 'us'
/uk // where the 'uk' parameter can be either 'uk' or 'us'
/ // in this case, I just want the region to default to 'uk'
The results I'm getting are not ideal though. the first one (/uk/home), and the third one (/) both work, but the second one (/uk), returns 404.
The configurations are defined as:
routes.MapRoute(
null,
"{region}/{controller}",
new { region = "^UK|US$" },
new { controller = "Home", action = "Index" }
);
routes.MapRoute(
null,
"{region}",
new { region = "^UK|US$" },
new { controller = "Home", action = "Index" }
);
routes.MapRoute(
null,
//"{region}",
"",
new {region = "UK", controller = "Home", action = "Index" }
);
What do i need to do to ensure that all 3 urls will default to the home page, with the empty URL defaulting the region to 'uk'?
Try the following routes:
routes.MapRoute(
"Region",
"{region}/{controller}",
new { controller = "Home", action = "Index" },
new { region = "^UK|US$" }
);
routes.MapRoute(
"Default",
"",
new { controller = "Home", action = "Index", region = "UK" }
);