Routing issues in asp.net MVC 4 - asp.net

I am a beginner in MVC 4. I have an url ../Home/NameDetailsPage/20 where controller= Home, action=NameDetailsPage and pageIndex= 20. How do i write my route engine for this url?
routes.MapRoute(
......
.....
);
In controller, NameDetailsPage works pretty fine for default page such as int page=2 :-
public ActionResult NameDetailsPage(int? page)
{
var context = new BlogContext();
IQueryable<string> list;
list = from m in context.Blogs.OrderBy(m => m.BlogId)
select m.Name;
ViewBag.total = list.ToArray().Length;
ViewBag.page = page;
var pageNumber = page ?? 1;
ViewBag.page1 = pageNumber;
return View("NameDetails", list.Skip(pageNumber * 4).Take(4));
}
But the pageNumber is always 1 whatever pageIndex in the url. So It shows same result for all the pageIndex. How can I set pageNumber other than 1. Thanks in Advance.

When you have a route like the following
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
);
The defaults object properties (controller, action, id) are what can be passed to the action (if the action has parameters that match the name).
So if you have an action:
public ActionResult NameDetailsPage(int? page)
there are no values being passed from the URL as page.
You can either change {id} to {page}, or preferably:
public ActionResult NameDetailsPage(int? id)

Based on your comment you are most of the way there. You just need to define the parameter you are passing to the action. In this case switching {id} for {page} and altering the defaults to suit.
routes.MapRoute(
name: "Page",
url: "Home/NameDetailsPage/{page}",
defaults: new { controller = "Home", action = "NameDetailsPage", page = UrlParameter.Optional } );

Related

How does RedirectToRoute work and how to pass data in it?

I'm trying to redirect to a route that is in the RecomController and the action is Index, i have defined the path in my RouteConfig file and have also specified an id parameter that i pass when i call my RedirectToRoute function. For some reason it can't find that path.
I have also created a Route attribute above the RecomController Index action but it still doesn't navigate me to that path. Am i missing something?
RouteConfig.cs:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Recomroute",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Recom", action = "Index", id = UrlParameter.Optional }
);
}
RecomController.cs:
[Route("Recom/Index")]
public ActionResult Index(int id)
{
............//Functioning
}
Calling the function (IN ANOTHER CONTROLLER):
ProjectController.cs:
return RedirectToRoute("Recom/Index/{id}", new {id = projectdto.Id });
Sounds like you're using wrong route name or path in RedirectToRoute(), hence it doesn't work:
// this is wrong because first parameter did not match
return RedirectToRoute("Recom/Index/{id}", new {id = projectdto.Id });
For two parameters overload, it requires route name (not route path) and route values, as shown in definition below:
protected internal RedirectToRouteResult RedirectToRoute(string routeName,
RouteValueDictionary routeValues)
Hence, you need to provide complete route name and route values defined in RegisterRoutes (e.g. Recomroute).
return RedirectToRoute("Recomroute", new {
controller = "Recom",
action = "Index",
id = projectdto.Id
});
Side notes:
1) You still need to provide controller, action and id parameters in order to match route definition.
2) The Recomroute seem defined below default route with same route segments definition which overrides all custom routes beneath it, if you want to evaluate Recomroute first move it to the top order and use different path against default route.

ASP.NET MVC 5 Routing issue using PagedList package

I am using the PagedList package to create a paging section for my tables.
Everything is working fine, but my urls are shown as:
http://localhost:55808/suppliers?page=2&sortOrder=id_desc&searchFilter=s
So I created a custom route for this using the following code:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.LowercaseUrls = true;
// Index Suppliers with paging / search filter / orderby
routes.MapRoute(
"SupplierPaging",
"suppliers/{searchFilter}/{sortOrder}/{page}",
new
{
controller = "Suppliers",
action = "Index",
sortOrder = UrlParameter.Optional,
searchFilter = UrlParameter.Optional,
page = 1
}
);
// Default route
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Also this is working for the Index of my Suppliers controller.
Now if I go to the http://localhost:55808/suppliers/edit/1 page to edit a supplier, it goes into the Index method of my controller instead of the Edit.
Do I need to add all these methods as custom routes to get it working? Eg:
A custom route for edit
A custom route for delete
...
Or what am I missing here?
Add route constraints so the first route will not match for other actions:
routes.MapRoute(
"DefaultPaging",
"{controller}/{searchFilter}/{sortOrder}/{page}",
new
{
action = "Index",
sortOrder = UrlParameter.Optional,
searchFilter = UrlParameter.Optional,
page = 1
},
new
{
sortOrder = #"\d+",
searchFilter = #"\d+",
page = #"\d+"
}
);
Also I've replaced "suppliers" part of the route with "{controller}", so this will work for all controllers with paging.

In asp.net MVC if the url has a parameter , does the route have to be registered?

In my limited (2 weeks) experience in asp.net MVC3, for most action methods, I have never needed to add a route registration. But I have noticed that if the action method has an input parameter, then I can't access the method with a url of the form www.mysite.com/myController/myAction/myParameter1/myParameter2/myParameter3 (without the ? mark ) unless I map the route. Is that how its supposed to be?
By default, you already have registered route:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
it accepts one parameter, named id, so your action:
public ActionResult MyAction(string id)
will "catch" the request:
www.mysite.com/MyController/MyAction/parameter_value
and id will get value "parameter_value".
If you need more than one parameter (or parameter has to be names something else than "id"), then you have to register new route.
In case when you have 2 parameters, you will register route like this:
routes.MapRoute(
"Default",
"{controller}/{action}/{parameter1}/{parameter2}",
new { controller = "Home", action = "Index", parameter1 = UrlParameter.Optional, parameter2=UrlParameter.Optional }
);
and your action might be:
public ActionResult MyAction(string parameter1, int? parameter2)
Yeah, you need to register the route customizing the route in global.asax according to your requirement.You have to register the route in following way:
routes.MapRoute(
"routeName", // Route name
"{controller}/{action}/{myParameter}", // URL with parameters
new { controller = "Home", action = "Index", myParameter= "" } // Parameter defaults
);
So with above route, it ensures that whenever your url goes in above format, the parameter right after "action/" will be taken as parameter.....
For more than one parameter in your url, you can register like this:
routes.MapRoute(
"routeName", // Route name
"{controller}/{action}/{myParameter1}/{myParameter2}/{myParameter3}", // URL with parameters
new { controller = "Home", action = "Index", myParameter1= "", myParameter2= "", myParameter3= "" } // Parameter defaults
);

MVC 3 Routes: Dynamic content from home controller - Where am I going wrong?

My Setup
I have a set of controllers in the normal fashion, which have their usual CRUD action methods inside them. Examples of these controllers are Testimonials, Galleries, and FAQs. These have backing models in Entity Framework, such as Testimonial, Gallery and FAQ, respectively.
You get to these by this sort of URL: /Galleries/Edit/2
All good so far, and all by default conventions...
I also have a set of pages that need to have editable content in them, and these have their content populated from a database via Entity Framework. They use an EF model behind them called "Page". This has a content property (html), and a name property so that I can match the incoming request. These pages are the Home, About and Prices pages.
I have chosen the Home controller to do this - I intend to have the index Action work out which Page to load from the DB by a name parameter:
[AllowAnonymous]
public ActionResult Index(string name = "Home")
{
// look up the page by name in the DB.
var model = context.Pages.FirstOrDefault(p => p.Title == name);
// trap errors.
if (model == null)
{
return RedirectToAction("NotFound", "Error", new { aspxerrorpath = name } );
}
// normal path
return View(model);
}
So, I could in theory add new items to the Pages table/DbSet and these would get mapped properly to this controller and action. I will then add an edit action for admin to edit the content that has the same signature as the index action above.
The Problem
The issue comes with Routing requests...
I had 2 initial routes:
routes.MapRoute("DynamicAccess",
"{name}/{action}",
new { controller = "Home", action = "Index" });
routes.MapRoute("Default",
"{controller}/{action}/{id}",
new { controller = "Home", action="Index", id=UrlParameter.Optional});
This fails when I go to "Galleries/", as it goes through the Home controller each time, and fails if I swap them around. I was also getting requests for Scripts/ folder through to the home controller too....
My Temporary Solution
My current routes now look like this:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("favicon.ico");
routes.MapRoute("Gallery",
"Gallery/{action}/{id}",
new { controller = "Galleries", action = "Index", id = UrlParameter.Optional });
routes.MapRoute("Testimonials",
"Testimonials/{action}/{id}",
new { controller = "Testimonials", action = "Index", id = UrlParameter.Optional });
routes.MapRoute("FAQs",
"FAQs/{action}/{id}",
new { controller = "FAQs", action = "Index", id = UrlParameter.Optional });
routes.MapRoute("DynamicAccess",
"{name}/{action}",
new { controller = "Home", action = "Index" });
routes.MapRoute("Default",
"{controller}/{action}/{id}",
new { controller = "Home", action="Index", id=UrlParameter.Optional});
routes.MapRoute("Root",
"",
new { controller = "Home", action = "Index" });
routes.MapRoute("AdminAccess",
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
new { authenticated = new AuthenticatedAdminRouteConstraint() });
You can see here that I've had to declare a route for each of my static pages above the route for the dynamically resolved Home Route.
Question
This looks clumsy to me - having to add each non-dynamic page to my routes table.
Can anyone point me to a cleaner way of doing this please?
Thanks in advance.
Why not put a constraint on your static routes, which will allow routes that don't match to fall through to the dynamic route?
routes.MapRoute("default",
"{controller}/{action}/{id}",
new {controller="home", action="index", id=UrlParameter.Optional},
new {controller="^(|home|gallery|testimonial|faq)$"});
routes.MapRoute("dynamic",
"{name}/{action}",
new {controller="home", action="index"});
You will have to change your controllers to match the singular name in the constraint but other than that, it ought to work.

ASP.NET MVC3 Route - example.com/blog/projects to example.com/projects

I have an ActionResult in my Blog controller that is returning all the projects called Projects, but my URL looks like example.com/blog/projects, I want to set up route to make it look like example.com/projects.
Is it possible? And if it is then how can I achieve that?
You have to register route following way Global.asax and put this as a first route
routes.MapRoute("Projects", "Projects" , new { controller="blog" , action="Projects" });
You can add a route to your Global.asax.cs file, such as:
routes.MapRoute(
"Projects", // Route name
"Projects/{id}", // URL with parameters
new { controller = "Blog", action = "Projects", id = UrlParameter.Optional } // Parameter defaults
);
So it looks something like this:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Projects", // Route name
"Projects/{id}", // URL with parameters
new { controller = "Blog", action = "Projects", id = 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
);
}
Make sure you put your new route above the default one otherwise yours will never be hit.

Resources