8

As the title says I'm looking for some help in that task, I've read many tutorials about it but none of them can solved my problem which is how to load a dropdownlistfor from database. By far, I got the following code:

**LNClientes():**

public List<ENDistrito> DistritoListar()
{
    return new ADClientes().DistritoListar();
}

**ADClientes():**

public List<ENDistrito> DistritoListar()
        {
            Database oDatabase =                      DatabaseFactory.CreateDatabase(ConfigurationManager.AppSettings["conexionBD"]);
            DbCommand odbcommand = oDatabase.GetStoredProcCommand("USP_SEL_DISTRITOS");

            List<ENDistrito> lista = new List<ENDistrito>();
            using (IDataReader reader = oDatabase.ExecuteReader(odbcommand))
            {
                while (reader.Read())
                    lista.Add(new ENDistrito(reader));
            }
            return lista;
        }

**Controller:**

 public ActionResult Registrar()
        {
            ViewBag.Message = Resources.Language.Title_Page_MC_C;
            var ListaDistrito = new LNClientes().DistritoListar();
            ViewBag.ObtenerDistrito = new SelectList(ListaDistrito, "IdDistrito", "DescripcionDistrito");
            return View();
        }

View:

<div class="editor-field">
            @Html.EditorFor(model => model.DistritoCliente)
            @Html.DropDownListFor(model => model.DistritoCliente,(SelectList)ViewBag.ObtenerDistrito,"--Seleccione--")
            @Html.ValidationMessageFor(model => model.DistritoCliente)
        </div>

Till this point everything is ok, when i open that form the dropdownlistfor works but when i submit the form i got the following message:

There is no ViewData item of type 'IEnumerable' that has the key 'DistritoCliente'.

Any idea on what I'm doing wrong or how could i solve this problem.

Thanks in advance.

Alex

3
  • How come you're using a data reader when you're just reading all your data into a list at one time? Commented Sep 23, 2013 at 15:53
  • Does stackoverflow.com/questions/2849341/… solve your problem? Commented Sep 23, 2013 at 15:56
  • i followed the article and still have not solve my problem ~ i changed some things like in controller im doing this: ViewData["Distritos"] = new SelectList(new LNClientes().DistritoListar(), "IdDistrito", "DescripcionDistrito"); but the problem still is the declaration of the dropdownlist which is @Html.DropDownListFor(Model=> Model.DistritoCliente,((SelectListItem)ViewData["Distrito"])) but it throws error of arguments, any other idea to solve it Commented Sep 23, 2013 at 16:49

2 Answers 2

20

How I commonly build my dropdowns are like this

@Html.DropDownListFor(x => x.Field, PathToController.GetDropDown())

and then in your controller have a method built like this

public static List<SelectListItem> GetDropDown()
    {
        List<SelectListItem> ls = new List<SelectListItem>();
        lm = (call database);
        foreach (var temp in lm)
        {
            ls.Add(new SelectListItem() { Text = temp.name, Value = temp.id });
        }
        return ls;
    }

Hopefully it helps.

Sign up to request clarification or add additional context in comments.

5 Comments

What is PathToController?
put in your controller name and type ctrl-. that will bring in the full path to your controller (project, area, contoller, something like that)
Glad to help. would you mind marking my answer as the correct answer?
I forgot a thing, what about if want to display a label which says "Choose an item"?
one of the options for the dropdownlistfor is that first item in the dropdown. I don't remember which item in the list it is. It might just be ... GetDropDown(), "Choose an item")
4

Controller:

ViewBag.States = new SelectList(db.States, "StateID", "StateName");

View: (In your view write the code for dropdown like this)

@Html.DropDownListFor(m => m.Address.StateID,ViewBag.States as SelectList,"--Select State--")

--> Here Address in one of the tables in my database having StateID as one of its properties

This one worked perfectly for me.. Try it!!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.