views:

78

answers:

1

I have a simple wizard generated query in a LinqDataSource like this:

<asp:LinqDataSource ID="EvaluationsData" runat="server" ContextTypeName="Bonus.Models.BonusDataContext"
    Select="new (Id, Name, Coverage)" TableName="BM_Evaluations" 
</asp:LinqDataSource>

I assign this data source to a DropDownList, using Id and Name as the DataValueField and DataTextField respectively. But when I selected a option, I want to keep the Coverage too, extracting it from the data source and storage in a HiddenField. It's a way to do this without making another query to the database?

Thanks.

A: 

To do this, you'll need to intercept the returned list of items from the data source and then manually assign Coverage to the items in the drop-down's items.

Here's your markup

<asp:LinqDataSource ID="EvaluationsData" runat="server"
    ContextTypeName="Bonus.Models.BonusDataContext"
    Select="new (Id, Name, Coverage)" TableName="BM_Evaluations"
    onselected="EvaluationsData_Selected">
</asp:LinqDataSource>
<asp:DropDownList ID="DropDownList1" runat="server" 
    DataSourceID="EvaluationsData" DataValueField="Id" DataTextField="Name"
    ondatabound="DropDownList1_DataBound">
</asp:DropDownList>

Here's your code

List<object> evaluations;
protected void EvaluationsData_Selected(object sender, LinqDataSourceStatusEventArgs e)
{
    evaluations = new List<object>(e.Result as IEnumerable<object>);
}
protected void DropDownList1_DataBound(object sender, EventArgs e)
{
    foreach (ListItem item in DropDownList1.Items)
    {
        var eval = evaluations.Where(a => a.Id == item.Value).FirstOrDefault();
        if (eval != null)
        {
            item.Attributes.Add("Coverage", eval.Coverage);
        }
    }
}
Jacob Proffitt