Search code examples
asp.netentity-frameworkasp.net-mvc-4paginationskip

MVC 4 skip function with variable shows unwanted error


I want to create a pagination in MVC 4 with entity data model. My Home/NameDetailsPage works fine which return me all the rows at a time. But I want to show this data with pagination as there are so many rows. So i have tried like this

 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;

        return View("NameDetails", list.Skip(page * 4).Take(4));
    }

here page number indicates that I want to skip page*4 rows to get the next 4 rows. Unfortunately I have found these error.

The parameters dictionary contains a null entry for parameter 'page' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult NameDetailsPage(Int32)' in 'webpro.Controllers.HomeController'.
An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters

What should I do ? Thanks in advance.


Solution

  • The error gives you the answer; page is a non-optional parameter. In other words the routing engine cannot find a suitable parameter-less action method, or an action method with optional parameters.

    You need to set page as an optional parameter

    public ActionResult NameDetailsPage(int page = 1)
    {
    ...
    

    Or pass the default value via a route definition.