Search This Blog

Saturday 13 May 2017

Unable to use strongly-typed views when using PagedList in MVC


Index.cshtml


Controller Action Method that returning a PagedList

public ActionResult Index(int? page)
        {
            BusinessLayer businessLayer = new BusinessLayer();
            List<FileUploadModel> fileUploadModel = businessLayer.GetDocument(search).ToList();
            int pageSize = 5;
            int pageNumber = (page ?? 1);
            return View(fileUploadModel.ToPagedList(pageNumber, pageSize));
        }

FileUploadModel class that containing the form propery

public class FileUploadModel
    {
        public string DocumentTitle { getset; }
        public string FileName { getset; }
    }


Solution:

Step 1:- Add IPagedList<FileUploadModel> property in FileUploadModel class.

using PagedList;

public class FileUploadModel
    {
        public string DocumentTitle { getset; }
        public string FileName { getset; }
        public IPagedList<FileUploadModel> iPagedUpdList { setget; }

    }

Step 2:- Change controller Action method

Note:- Instead of returning the paged list, return an object of this view model.

public ActionResult Index(int? page)
        {
            BusinessLayer businessLayer = new BusinessLayer();
            FileUploadModel fileUploadModel = new FileUploadModel();
            int pageSize = 5;
            int pageNumber = (page ?? 1);
            fileUploadModel.iPagedUpdList = businessLayer.GetDocument().ToPagedList(pageNumber, pageSize);
            return View(fileUploadModel);
        }

Step 3:- Change view


























Use Model.iPagedUpdList property to render the list of documents.

@foreach (var item in Model.iPagedUpdList)
{
    <tr>
        <td>@item.DocumentTitle</td>                    
        <td>@item.FileName</td>                    
    </tr>
}

instead of

@foreach (var item in Model)
{
    <tr>
        <td>@item.DocumentTitle</td>                    
        <td>@item.FileName</td>                    
    </tr>
}

No comments:

Post a Comment