null reference binding jqgrid to object that conta

2019-07-14 23:47发布

问题:

Does anyone know why the following c# mvc.net code gives a null ref exception when databainding the list to the jqgrid?

This is a cutdown example to illustrate the problem.

If I change DataField = "MyClass.Id" to DataField = "Id" It binds just fine, but in my real code I am trying to bind to an object with 2 subobjects and am trying to display data from both on the same grid.

Any suggestions much appreciated. Thanks

(I saw this post but it didn't get answered: jqgrid List of objects (with sub objects) as datasource)

internal class MyWrapper
{
    public MyClass MyClass { get; set; }
    public int Id { get; set; }
}

internal class MyClass
{
    public int Id { get; set; }
}

public class TestController : Controller
{
    public ActionResult Index()
    {
        return View(GetGrid());
    }

    public JsonResult SearchGridDataRequested()
    {
        return GetGrid().DataBind(GetModel().AsQueryable());
    }

    private JQGrid GetGrid()
    {
        return new JQGrid
                   {
                       ID = "MyGrid",
                       DataUrl = Url.Action("SearchGridDataRequested"),
                       Width = Unit.Pixel(700),
                       Columns = new List<JQGridColumn>
                                     {
                                         new JQGridColumn
                                             {
                                                 DataField = "MyClass.Id",
                                                 PrimaryKey = true,
                                                 DataType = typeof (int)
                                             }
                                     }
                   };
    }


    private static IEnumerable<MyWrapper> GetModel()
    {
        return new List<MyWrapper>
                   {
                       new MyWrapper {Id = 1, MyClass = new MyClass {Id = 11}},
                       new MyWrapper {Id = 2, MyClass = new MyClass {Id = 12}},
                       new MyWrapper {Id = 3, MyClass = new MyClass {Id = 13}}
                   };
    }
}