entity framework - Sorting a GridView on a navigation property that uses Model Binding in ASP.NET 4.5 -


model binding has lot of benefits , saves lot of time when want throw data gridview on page , , running quickly. example, can have employee class

public class employee {     public int id { get; set; }     public string name { get; set; }     public virtual icollection<job> jobs { get; set; }      [notmapped]     public job currentjob     {          { return jobs.orderbydescending(x => x.startdate).firstordefault(); }     } 

i throw gridview using model binding , template field calculated property:

<asp:gridview runat="server" id="gvdataitemtype" itemtype="model.employee" selectmethod="select" allowsorting="true">     <columns>                     <asp:dynamicfield datafield="name"/>         <asp:dynamicfield datafield="email"/>             <asp:templatefield headertext="job" sortexpression="???">             <itemtemplate>                 <asp:label id="lbljobtitle" text='<%# bind("currentjob.jobname") %>'></asp:label>             </itemtemplate>         </asp:templatefield>         ... 

with following select method in code behind:

public iqueryable<employee> select() {     mycontext context = new mycontext();     return context.employees; }     

everything sorts wonderfully except, obviously, currentjob.jobname property.

my question is: how can sort gridview on currentjob.jobname property?

i think can answer own question. added unique sort expression template field didn't correspond existing sort expression:

<asp:templatefield headertext="job" sortexpression="meaninglesssortexpression">             <itemtemplate>                 <asp:label runat="server" id="lbljobtitle" text='<%# bind("currentjob.job.jobname") %>'></asp:label> 

and discovered gridview's selectmethod argument this:

select(string sortbyexpression) 

then threw conditional logic right select method. no need deal onsorting or that:

public iqueryable<employee> select(string sortbyexpression)     {         mycontext context = new mycontext ();         if (sortbyexpression == "meaninglesssortexpression")         {                             return context.employees.orderby(x => x.jobs.orderbydescending(y => y.startdate).firstordefault().job.jobname);         } 

it's little verbose, couldn't run linqquery based on x => x.currentjob since it's calculated property. anyway worked. didn't need manually call databind(); caveat apparently overrides default sort functionality, can reproduce this:

else { return context.employees.sortby(sortbyexpression);  

this helpful: asp.net 4.5 model binding sorting navigation property


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -