How to retrieve value from DropDownListFor html helper in ASP>NET MVC2?

Posted by Eedoh on Stack Overflow See other posts from Stack Overflow or by Eedoh
Published on 2010-04-23T09:48:58Z Indexed on 2010/04/23 9:53 UTC
Read the original article Hit count: 1270

Hello

I know there was few similar questions here about DropDownListFor, but neither helped me...

I use Entity Framework as ORM in my project. There's EF model called "Stete". Stete has Foreign on EF model called "Drustva"

Now I'm trying to make a form for editing the data, for Stete model. I managed to display everything, including Stete.Drustva.Naziv property, but I can't get this last property in my handler method [HttpPost]. It always return 0, no matter what I select in drop down list.

Here's the code:

DrustvaController:

 public static IEnumerable<SelectListItem> DrustvaToSelectListItemsById(this KnjigaStetnikaEntities pEntities, int Id)
    {
        IEnumerable<Drustva> drustva = (from d in pEntities.Drustva
                                        select d).ToList();
        return drustva.OrderBy(drustvo => drustvo.Naziv).Select(drustvo => new SelectListItem
        {
            Text = drustvo.Naziv,
            Value = drustvo.Id.ToString(),
            Selected = (drustvo.Id == Id)? true : false
        });
    }

SteteController:

        private IEnumerable<SelectListItem> privremenaListaDrustava(int Id)
        {
        using (var ctx = new KnjigaStetnikaEntities())
        {
            return ctx.DrustvaToSelectListItemsById(Id);
        }
    }

public ActionResult IzmijeniPodatkeStete(Int32 pBrojStete)
    {
        PretragaStetaModel psm = new PretragaStetaModel();
        ViewData["drustva"] = privremenaListaDrustava(psm.VratiStetuPoBrojuStete(pBrojStete).Drustva.Id);

        ViewData.Model = new Models.Stete();

        return View("EditView", (Stete.Models.Stete)psm.GetSteta(pBrojStete));
    }

EditView:

        <div class="editor-label">
            <%: Html.Label("Društvo") %>
        </div>
        <div class="editor-field">
            <%: Html.DropDownListFor(m => m.Drustva.Naziv, ViewData["drustva"] as IEnumerable<SelectListItem>) %>
            <%: Html.ValidationMessageFor(model => model.FKDrustvo) %>
        </div>

I am sorry for not translating names of the objects into english, but they hardly have appropriate translation. If necessary, I can try creating similar example...

© Stack Overflow or respective owner

Related posts about asp.net-mvc

Related posts about asp.net-mvc2