0

Question Background:

I have a URL that contains a parameter called pageNo that is sent to a controller called Events with a method called FutureEvents that is being called. This is used with pagination to determine the page number of a view that needs to be shown. This is the URL:

http://localhost:xxxxx/Events/FutureEvents?pageNo=1

The Issue:

If the user manually types the URL and doesn't supply the page number parameter in the URL, for example:

http://localhost:51025/Events/FutureEvents

then an ASP error shows with the message:

The parameters dictionary contains a null entry for parameter 'pageNo' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult FutureEvents(Int32)'

This makes sense as the parameter is null. What I want to do is redirect the user to another controller (in this case my Home Controller and Index method) when the user tries to call the FutureEvents controller and Events method with an empty pageNo parameter.

This is my current route:

 routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

The Home Controller with its Index method - this is what I want to redirect to.

 public ActionResult Index()
 {
    return View();
 }

The FutureEvents Controller with the Events method:

 [HttpGet]
 public ActionResult FutureEvents(int pageNo)
 {
     //code
 }
adricadar
  • 9,971
  • 5
  • 33
  • 46
user1352057
  • 3,162
  • 9
  • 51
  • 117

3 Answers3

3

If you pass the parameter in function we need put then or set a initial value.

int pageNo = 0 or int? pageNo

   [HttpGet]
     public ActionResult FutureEvents(int pageNo = 0)
     {
         //code
     }

all others functions without parameters open normally.

2

You have to define two routes, one with parameter (not optional) and one without parameter.

routes.MapRoute( // because id is required, route will be skipped
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Events", action = "FutureEvents"}
    );

routes.MapRoute( // catch all routes that doesn't match the others.
        name: "CatchAll",
        url: "{*everything}",
        defaults: new { controller = "Home", action = "Index" }
    );

You can see this answer for more informations.

Community
  • 1
  • 1
adricadar
  • 9,971
  • 5
  • 33
  • 46
0

or if you want use the session to pass the page number in this way their is no worry about editing the page number by the user

Session["Pagenumber"]=value;

//redirect to an action