sharif2008
sharif2008

Reputation: 2798

Routing issues in asp.net MVC 4

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.

Upvotes: 1

Views: 555

Answers (2)

Erik Philips
Erik Philips

Reputation: 54628

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)

Upvotes: 1

Brent Mannering
Brent Mannering

Reputation: 2316

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 } );

Upvotes: 0

Related Questions