1

I tried to make a simple web app to display a grid with data from a .mdf database. However, it seems that I am returning the "model" (derived from "source") as null.

HomeController.cs:

public List<BooksTable> GetBooks(string search, string sort, string sortdir, int skip, int pageSize, out int totalRecord){
    using(MyDatabaseEntities dc = new MyDatabaseEntities()){
        var v = (from a in dc.BooksTables
            where 
                a.Author.Contains(search) || 
                a.Title.Contains(search) ||
                a.Year.ToString().Contains(search)
           select a);
        totalRecord = v.Count();
        v = v.OrderBy(sort + " " + sortdir);
        if(pageSize > 0)
            v = v.Skip(skip).Take(pageSize);
        return v.ToList();
    }
}

Index.cshtml:

@model List<LibraryP3.BooksTable>

@{
    Layout = null;
    var grid = new WebGrid(canPage: true, rowsPerPage: 10);
    grid.Bind(source: Model, rowCount: ViewBag.TotalRows, autoSortAndPage:false);
}

This is the error I get after running it: System.ArgumentNullException: 'Value cannot be null. Parameter name: source'

[EDIT - Added Action Method]


    public ActionResult Index(int page = 1, string sort = "Author", string sortdir = "asc", string search = ""){
        int pageSize = 10;
        int totalRecord = 0;
        if (page < 1)
            page = 1;
        int skip = (page * pageSize) - pageSize;
        var data = GetBooks(search, sort, sortdir, skip, pageSize, out totalRecord);
        ViewBag.TotalRows = totalRecord;
        ViewBag.search = search;
        return View();
    }
  • We are missing the Action method here, and that is where it all happens. – H H Jun 08 '19 at 20:20
  • It looks like the v variable is null. You need to step through your code in the controller to see why the v variable is null. https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it – Jake Steffen Jun 08 '19 at 20:32
  • @HenkHolterman just added it. Am I missing somewhere the binding here of the List to be set as the "model"? – André Mateus Jun 08 '19 at 20:40

0 Answers0