c# - @Html.DisplayFor() is not working with custom model sub-class -
so have mvc application manage list of sites , on details view none of sub classes within model render though @html.displaynamefor rendering label correctly.
here view code working fine:
<tr> <td> <span class="label label-info">@html.displaynamefor(model => model.sitename)</span> </td> <td style="text-align: center;"> @html.displayfor(model => model.sitename) </td> </tr>
this code displayfor generates nothing:
<tr> <td> <span class="label label-info">@html.displaynamefor(model => model.version.versionname)</span> </td> <td style="text-align: center;"> @html.displayfor(model => model.version.versionname) </td> </tr>
here site model:
public class site { public int id { get; set; } [required] [display(name = "link")] [datatype(datatype.url)] public string sitelink { get; set; } [required] [display(name = "name")] public string sitename { get; set; } public int versionid { get; set; } [foreignkey("versionid")] public version version { get; set; } }
and version class:
public class version { public int id { get; set; } [display(name = "version")] public string versionname { get; set; } public list<site> sites { get; set; } }
lastly, here details actionresult method in controller:
public actionresult details(int id = 0) { site site = db.sites.find(id); if (site == null) { return httpnotfound(); } return view(site); }
all of other views rendering fine, details view seems returning nothing custom classes.
you need explicitly load child (version):
site site = db.sites.find(id); if (site == null) { return httpnotfound(); } db.entry(site).reference(p => p.version).load(); return view(site);
you
db.sites.include(s => s.version).firstordefault(s => s.id == id);
https://msdn.microsoft.com/en-us/data/jj574232.aspx#explicit
Comments
Post a Comment