1

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.

2
  • What routing have you tried? What did you see that was different to what you expected? Commented Sep 16, 2013 at 21:08
  • routes.MapRoute( name: "Page", url: "Home/NameDetailsPage/{id}", defaults: new { controller = "Home", action = "NameDetailsPage", id = UrlParameter.Optional } ); Commented Sep 16, 2013 at 21:10

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah I gor it . Thanks a lot @erik
0

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

1 Comment

Thanks brent for your easy explanation. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.