开发者

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


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?


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜