I have an entity called Lookup who has a complex Type Description with two string English and French. There has arise a time where no value will be store into the lookup. Now other entities have lookups as properties so we could have foo.Lookup.Description.English for example.
I'm trying to use a Web Grid to display the information being selected.
Originally my controller looked like
public ViewResult Index()
{
var foos = db.Foos;
return View(foo.ToList());
}
and my view looked like
@model IEnumerable<Foo>
@{
ViewBag.Title = "Index";
}
<h2>Stay Manager</h2>
@{
var grid = new WebGrid(Model, defaultSort: "sortMe", rowsPerPage: 3);
grid.GetHtml(htmlAttributes: new { id = "DataTable" });
}
@grid.GetHtml(columns: grid.Columns(
grid.Column("Lookup.Description.English", "Column Header")
))
My issue is that Lookup can at times be null and ill will get an error saying the the Column Lookup.Description.English does not exist.
I found a solution but not a very elegant one and was hoping that there was a better a way. My solution was to change my controller action to
public ViewResult Index()
{
var foos = db.Foos;
foreach (Foo currentFoo in Foos.Where(s => s.Lookup == null))
{
Foo.Lookup = new Lookup();
Foo.Lookup.Description.English = "";
Foo.Lookup.Description.French = "";
}
return View(foos.ToList());
}
Any suggestions on how to get the Web Grid to work better with null-able complex types?