Search code examples
c#asp.net-mvcentity-frameworkwebgrid

WebGrid - Sorting by navigation property's field when null reference


I'm using System.Web.Helpers.WebGrid to display an IEnumerable<Request>. Requests have some navigation properties.

Whenever I sort by clicking in the title by any of those's field, exception Object reference not set to an instance of an object. rises.

I code this type of columns this way:

grid = new WebGrid(Model.Requests);

// things

@grid.GetHtml(columns: new[]{
    //[...] columns
    SDMs.Column("User.Name", "User", format: p => p.User != null ? p.User.Name : ""),
    //[...] more columns
})

Note that I'm using the format parameter to set a custom result on grid loading.

I think this happens because of the rows that don't have an User associated, but I don't know how to customize the behaviour on these cases.

I found out this on the web, but I don't seem to have this method in my version of the assembly. I don't know how to get it either. I tryed installing NuGet packages but didn't help.

Any ideas?


Solution

  • Add an extension method/ partial class's property for the Request, like ActualOrEmptyUserName. And in the Getter, you can check the User is populated or not, if so return user.name else return "".

    And in your grigview, you tie the column to the ActualOrEmptyUserName insetad of user.name

    public partial class Request
        {
            public string ActualOrEmptyUserName 
            {
                get
                {
                    var username = "";
                    if (Request.User != null && Request.User.Name != null)
                        username = Request.User.Name;
    
                    return username;
                }
            }
        }
    
    ...
    
    SDMs.Column("ActualOrEmptyUserName", "User")
    

    Another option: Itarete (or linq) trough your list, and check the value of user, if it is null, then create an empty user to that value and fill the Name with string.empty or "".

    This itaration can be in you controller or the upper part of the view. this is up to you.

    But i guess you cannot use the format like as you tried.