Dale
Dale

Reputation: 11

DropDownList item not selected

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

Upvotes: 1

Views: 914

Answers (2)

bytebender
bytebender

Reputation: 7491

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"])%>

Upvotes: 0

LukLed
LukLed

Reputation: 31882

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?

Upvotes: 1

Related Questions