I have read here : Routing with Multiple Parameters using ASP.NET MVC. But still not worked in my case.
I have EmitenController which there a function like this:
public async Task<ActionResult> Financial(string q = null, int page = 1)
At first load, the URL that produced by this function: Emiten/Financial?q=&page=1.
The next page of course Emiten/Financial?q=&page=2.
If I give the query that URL become: Emiten/Financial?q=query&page=1 and go on.
For the routes, I have tried
routes.MapRoute(
name: "Financial",
url: "{controller}/{action}/{q}/{page}",
defaults: new { controller = "Emiten", action = "Financial", q = "", page = 1 }
);
But, when I try go to page 3 the URL still Emiten/Financial?q=&page=2 and how about the URL if I give q empty value?
Thanks in advance.
I can't seem to reproduce your issue. Are you sure you mapped your Financial route before your Default one?
Here is my RegisterRoutes method:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Financial",
"{controller}/{action}/{q}/{page}",
new { controller = "Emiten", action = "Financial", q = string.Empty, page = 1 }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Here is the Controller:
public class EmitenController : Controller
{
public async Task<ActionResult> Financial(string q, int page)
{
return View();
}
}
(I know the async is useless in this case, but you can't await a ViewResult)
And here is the View:
q = #Request.QueryString["q"]<br/>
page = #Request.QueryString["page"]
#Html.ActionLink("Page 2", "Financial", "Emiten", new { q = "test", page = 2 }, null)
<br/>
Page 3
Everything works as expected
If the route is for a specific action method, then you should specify the action method directly in the URL settings
routes.MapRoute(
name: "Financial",
url: "Emiten/Financial/{q}/{page}", // <---- Right here
defaults: new
{
controller = "Emiten",
action = "Financial",
q = string.Empty, // string.Empty is the same as ""
page = 1,
}
);
In your action method, you don't need to specify the default values since you already did that in your route config.
public async Task<ActionResult> Financial(string q, int page)
Let me know how it works for you
UPDATE:
Generating a link relative to a route
#Html.RouteLink(
linkText: "Next Page",
routeName: "Financial",
routeValues: new { controller = "Emiten", action = "Financial", q = ViewBag.SearchKey, page = nextPage})
Related Link: What's the difference between RouteLink and ActionLink in ASP.NET MVC?
Related
I am trying to do some MVC routing, following online tutorials, but for some reason the routing is not working.
I am trying to do http://www.website.com/news/news-title
The route I am trying to do is below.
routes.MapRoute(
"News",
"{controller}/{url}",
new { controller = "News", action = "Index", url = "" }
);
Within my NewsController I have the following ActionResult.
public ActionResult Index(String url)
{
return View();
}
However, when stepping thorough the code, url is not being populated.
Thanks
== Update ==
Thank you all for your replies.
I have no amended the Route to below
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.LowercaseUrls = true;
routes.Add(new SubdomainRoute());
routes.MapRoute(
"News",
"News/{action}/{slug}",
new { controller = "News", action = "Index" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
This URL works: /news/index/?slug=test-news-title
But this URL does not: /news/index/test-news-title
=== Further Edit ===
It appears my subdomain route is messing with it. If i remove the subdomain route it works fine.
Thanks.
Most likely, your route is too broad. But it depends on how the rest of your routes are configured. You would need to post your entire route configuration (including area routes and attribute routing) in order to reasonably get an answer what is wrong with your route.
However, you can be more specific with this route because you know that it needs to start with /News.
routes.MapRoute(
"News",
"News/{url}",
new { controller = "News", action = "Index" }
);
Also, it probably doesn't make sense to make the URL parameter optional by providing a default value. If you remove url = "", the url parameter is required in the URL. If configured as above, if you just pass /News, it won't match this route. However, as you have it this URL will match.
Finally, make sure this route is placed in the right order. It should be placed before your default route (if you still have it).
You have set for the parameter url the empty string. you should use instead UrlParameter.Optional (or removing it at all if is mandatory):
routes.MapRoute(
"News",
"{controller}/{url}",
new { controller = "News", action = "Index", url = UrlParameter.Optional }
);
You are missing the action part in the MapRoute
routes.MapRoute(
"News",
"{controller}/{action}/{url}",
new { controller = "News", action = "Index", url = "" }
);
Hope this help
I have an MVC4 aplications with my routes defined in the RouteConfig working ok, like this:
routes.MapRoute(
"LocalizedDefault", "{lang}/{homePage}",
new { controller = "Home", action = "Index", pageCode = "home" },
new {lang = #"(en|es)", homePage = #"(home|inicio)"}
);
routes.MapRoute(
"Flowers",
"{lang}/{page}",
new {controller = "Plants", action = "Flowers", pageCode = "flowers"},
new {lang = #"(en|es)", page= #"(flowers|flores)"}
);
/* ... more routes ... */
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
as you can see every route has a parameter I need to change my languages (my business logic), the problem is that when I put the url without any parameters like http://www.mydomain.com, it loads my default page but I can't change the language because I don't have my page Parameter, then I change my routes:
routes.MapRoute(
"Flowers",
"{lang}/{page}",
new {controller = "Plants", action = "Flowers", pageCode = "flowers"},
new {lang = #"(en|es)", page= #"(flowers|flores)"}
);
/* ... more routes ... */
routes.MapRoute(
"Default",
"{lang}/{page}",
new { controller = "Home", action = "Index", pageCode = "home" },
new {lang = #"(en|es)", page = #"(home|inicio)"}
);
Now I have my site changing its language ok when call http://www.mydomain.com but the others routes don't work anymore (ex: http://www.mydomain.com/en/flowers)
Try with the default route and add a parameter to your url like this...
http://mydomain.com/?lang=es
Then on you Index action at your home controller...
public ActionResult Index(String? lang){
//do some stuff when lang != null
return View();
}
I have problems with generating URL with Html.RouteLink method using route.
My routes:
routes.MapRoute(
name: "DefaultPage",
url: "",
defaults: new { controller = "Home", action = "Index" }
);
routes.MapRoute(
name: "MessagesIndex",
url: "{controller}/{page}",
defaults: new { controller = "Messages", action = "Index", page = UrlParameter.Optional }
);
My controller(MessagesController) index method header:
public ActionResult Index(int page = 0)
And link generation:
#Html.RouteLink("Messages", "MessagesIndex")
I already tried ActionLink and Action...
EDIT: Sloved. Glimpse helped and MSDN. Its very important order of routes too.
Can you explain what problems you are having?
Maybe this will work:
#Url.Action("Index", "Messages")
I have an MVC3 site with 2 areas plus the common area. I also have a route specified for paginating lists of items. My Register_Routes method looks like so:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Paginate", // Route name
"{controller}/Paginate/{itemsPerPage}/{pageNumber}/{searchString}", // URL with parameters
new { controller = "Home", action = "Index", itemsPerPage = SiteSettings.ItemsPerPage, pageNumber = 1, searchString = UrlParameter.Optional } // Parameter defaults
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
What I've noticed (and don't understand) is if I log out from my home page, the redirect from my login page looks like
http://localhost:62695/Account/LogOn?ReturnUrl=%2fHome%2fPaginate
... and upon logging in, I end up on my home page, except with a URL of:
http://localhost:62695/Home/Paginate
I'm fairly certain at this point that I've screwed something up with the route map, but it seems right to me. What am I doing wrong?
UPDATE
per suggestion, I changed my routes to look like this:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Paginate", // Route name
"{controller}/Paginate/{itemsPerPage}/{pageNumber}/{searchString}", // URL with parameters
new { controller = "Home", action = "Index", searchString = UrlParameter.Optional } // Parameter defaults
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
... and the home index pages do indeed seem to work properly, but now the paginates don't:
return RedirectToAction("Paginate", new { itemsPerPage = SiteSettings.ItemsPerPage, pageNumber = 1, searchString = string.Empty });
in a Admin\HomeController yields the URL:
http://localhost:62695/Admin/Users/Paginate?itemsPerPage=25&pageNumber=1
so I'm still doing something wrong here.
UPDATE 2
OK, this is how I got it to work the way I wanted it to:
My RegisterRoutes method now looks like this:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
null,
"{area}/{controller}/Paginate/{itemsPerPage}/{pageNumber}/{searchString}", // URL with parameters
new {area = string.Empty, controller = "Home", action="Paginate", searchString = UrlParameter.Optional } // Parameter defaults
);
routes.MapRoute(
"Default", // Route name
"{area}/{controller}/{action}/{id}", // URL with parameters
new {area = string.Empty, controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
... but this was not enough to fix the routing issues. Additionally to this, I needed to add the route to my area registrations. My AdminAreaRegistration looks like this:
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
null,
"Admin/{controller}/Paginate/{itemsPerPage}/{pageNumber}/{searchString}", // URL with parameters
new { controller = "Home", action = "Paginate", searchString = UrlParameter.Optional } // Parameter defaults
);
context.MapRoute(
"Admin_default",
"Admin/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
This, in addition to changing to RedirectToRoute for my connections, made my URLs all pretty and working at the same time. All the answers helped to get to my goal, I +1'd everyone and chose the answer that got me closest to the path.
Routes are evaluated in the order they are registered. The redirects are being generated by the first route that you registered, especially since you declared default values for all of the segments. You might want to consider defining a more specific route
UPDATE
Use RedirectToRoute instead of RedirectToAction to get your desired URL generation
RedirectToRoute("Paginate", new { itemsPerPage = SiteSettings.ItemsPerPage, pageNumber = 1, searchString = string.Empty });
routes.MapRoute(null, // do not name your routes, it's a "magic string"
"{controller}/Paginate/{itemsPerPage}/{pageNumber}/{searchString}",
new
{
controller = "Home",
action = "Index",
searchString = UrlParameter.Optional
}
);
// instead of RedirectToAction, try RedirectToRoute, and do not use the route name
return RedirectToRoute(new
{
controller = "Home",
area = "AreaName",
itemsPerPage = SiteSettings.ItemsPerPage,
pageNumber = 1,
searchString = string.Empty,
}
);
Well, the reason you return to the URL http://localhost:62695/Home/Paginate is because when you log in you return to the URL specified, namely the ?ReturnUrl=%2fHome%2fPaginate part of http://localhost:62695/Account/LogOn?ReturnUrl=%2fHome%2fPaginate. Is that not the URL of your home page? You never specified.
It could be that the first definition takes precedence also, not sure where I heard that, so maybe if you put the default definition first it will grab that.
I've got some routing issues with MVC 2. Might be a simple problem, but I can't make it run. I have registered a second routing including the language:
routes.MapRoute(
// Route name
"LangRouting",
// URL with parameters
"{currentLang}/{controller}/{action}/{id}",
// Parameter defaults
new { currentLang = "de", controller = "Home", action = "Index",
id = UrlParameter.Optional }
);
routes.MapRoute(
// Route name
"Default",
// URL with parameters
"{controller}/{action}/{id}",
// Parameter defaults
new { controller = "Home", action = "Index"}
);
Now when I call {...}/de/Home/Index/ everything works fine. But if I leave the language away and call {...}/Home/Index/, the page can't be found ("The resource cannot be found."). I would have expected that this should run without language in the URL and that MVC would insert my default-value in there. How does it work else?
You must use constraint for language.
/Home/Index
will be translated into first rule as
lang = Home
controller = Index
action = Index (from defaults)
This should do the trick:
routes.MapRoute("Default with language", "{lang}/{controller}/{action}/{id}", new
{
controller = "Home",
action = "Index",
id = UrlParameter.Optional,
}, new { lang = "de|en" });
routes.MapRoute("Default", "{controller}/{action}/{id}", new
{
controller = "Home",
action = "Index",
id = UrlParameter.Optional,
lang = "en",
});