views:

128

answers:

2

I'm obviously still missing something about how to bind the selected item in a DropDownList.

I set up the SelectList like this in a repository:

    public SelectList GetAgencyList(System.Guid donorId, Int32 selected)
    {
        AgenciesDonorRepository adRepo = new AgenciesDonorRepository();
        List<AgenciesDonor> agencyDonors = adRepo.FindByDonorId(donorId);

        IEnumerable<SelectListItem> ad = from a in agencyDonors 
               select new SelectListItem {
                 Text = a.Agencies.AgencyName, 
                 Value = a.AgenciesDonorId.ToString() 
               };

        return(new SelectList(ad, "Value", "Text", (selected == 0 ? 0 : selected)));
    }

Then in the controller, this:

            ViewData["AgenciesDonorList"] = repo.GetAgencyList(donorId, ccResult.AgenciesDonors.AgenciesDonorId);
            return View(ccResult);

And in the view, this:

<%=Html.DropDownList("AgenciesDonorList", (IEnumerable<SelectListItem>)ViewData["AgenciesDonorList"])%>

In the debugger right before return View(...), I can see the proper item is selected (true) and all others are false. But in the view, the select option never makes it, and the first time is always shown.

Does this have nything to do with my use of int as the selected param?

Thx. Dale

+1  A: 

Change GetAgencyList to:

public SelectList GetAgencyList(System.Guid donorId, Int32 selected)
{
    AgenciesDonorRepository adRepo = new AgenciesDonorRepository();
    List<AgenciesDonor> agencyDonors = adRepo.FindByDonorId(donorId);

    var ad = from a in agencyDonors 
           select new {
             Text = a.Agencies.AgencyName, 
             Value = a.AgenciesDonorId
           };

    return(new SelectList(ad, "Value", "Text", selected));
}

ad doesn't have to be of type IEnumerable<SelectListItem>. Is AgenciesDonorId Int32?

LukLed
Thx. That seems to have helped. Also changed the first param in the DropDownList View method to 'AgenciesDonorId' instead of AgenciesDonorList. Together, it works.
Dale
Yes. "AgenciesDonorId" is the name of the form field being edited. As J.13.L said, casting ViewData["AgenciesDonorList"] to IQueryable<SelectListItem> should be replace with <SelectList>, because you supply SelectList:)
LukLed
A: 

I would have to agree with LukLed I am not sure what you are doing with the statement: (selected == 0 ? 0 : selected) If I pass in a 0 then it returns 0 and if I pass in something other than 0 then it uses that value.

Edit: Oh... I see it. Change the cast:

<%=Html.DropDownList("AgenciesDonorList", (IEnumerable<SelectListItem>)ViewData["AgenciesDonorList"])%>

To:

<%=Html.DropDownList("AgenciesDonorList", (SelectList)ViewData["AgenciesDonorList"])%>
J.13.L
Ah yes, several little problems in the end. Thx.
Dale