Lazy Loading In ASP .NET MVC

6/7/2018 3:38:52 PM

Lazy Loading In ASP .NET MVC

Lazy loading is a technique which loads the data on demand or when it is required. It improves efficiency and the performance of the application. Let's take a scenario, where we have 2 lakh of records and want to display them to the user. However, when you load 1 lakh of records at a time, it takes more time to render the result. It may be off putting to the user, while loading the records. In order to avoid the problem, either we need to use paging concept or lazy loading. Lazy loading loads the data step-by-step, when the user scrolls down the page, which is required by it.


public const int RecordsPerPage = 20;  

public List<Project> ProjectData;  

  

public HomeController()  

{  

    ViewBag.RecordsPerPage = RecordsPerPage;              

}  

  

public ActionResult Index()  

{  

    return RedirectToAction("GetProjects");  

}          

  

public ActionResult GetProjects(int? pageNum)  

{  

    pageNum = pageNum ?? 0;  

    ViewBag.IsEndOfRecords = false;  

    if (Request.IsAjaxRequest())  

    {  

        var projects = GetRecordsForPage(pageNum.Value);  

        ViewBag.IsEndOfRecords = (projects.Any());  

        return PartialView("_ProjectData", projects);  

    }  

    else  

    {  

        var projectRep = new ProjectRepository();  

        ProjectData = projectRep.GetProjectList();  

  

        ViewBag.TotalNumberProjects = ProjectData.Count;  

        ViewBag.Projects = GetRecordsForPage(pageNum.Value);  

  

        return View("Index");  

    }  

}  

  

public List<Project> GetRecordsForPage(int pageNum)  

{  

    var projectRep = new ProjectRepository();  

    ProjectData = projectRep.GetProjectList();  

  

    int from = (pageNum * RecordsPerPage);  

  

    var tempList = (from rec in ProjectData  

                    select rec).Skip(from).Take(20).ToList<Project>();  

  

    return tempList;  

}  


Add a Comment.