DropDownList Fill From Database

Hi,

I’m totally new to MVC, my god!!!, everything is totally different!!!, I’m going nuts with this change, so you will see me around very often, please have patience.

I am confused, I am trying to fill a DropDownList from a datatable (as I used to do in webforms), I have found a sample of doing it, so this is what I do:

- I created a class with 3 properties: Value as string, Display as string, DDList as Mvc.SelectList

- This is what I do in my controller:

 Function prices() As ActionResult

            Dim List = New List(Of BxDropDowns)()
            Dim Bx As New BxAccess
            Dim dt As DataTable = Bx.LoadProducts

            For Each row As DataRow In dt.Rows
                List.Add(New BxDropDowns With {.Value = row.Item("value"), .Display = row.Item("display")})
            Next

            Dim BxFact As New BxDropDowns
            BxFact.DDList = New SelectList(BxList, "value", "display")

            Return View(BxFact)

End Function

and in my view:

@Html.DropDownList("ddinv", CType(Model.BxFact, SelectList), New With {.Style = "width: 184px;", .onchange = "Check();"})

at the end it works ok, but something tells me I’m not doing it correctly and what if I have to fill more dropdownlists?, do I have to create a class for each one?

Thanks in advance for your help.

GeorgeClass

at the end it works ok, but something tells me I’m not doing it correctly and what if I have to fill more dropdownlists?, do I have to create a class for each one?

You do not have to write class.

send select list through ViewBag to view

GeorgeClass

BxFact.DDList = New SelectList(BxList, "value", "display")
ViewBag.DDList = New SelectList(BxList, "value", "display")


GeorgeClass

@Html.DropDownList("ddinv", CType(Model.BxFact, SelectList), New With {.Style = "width: 184px;", .onchange = "Check();"})
@Html.DropDownList("ddinv", CType(ViewBag.BxFact, SelectList), New With {.Style = "width: 184px;", .onchange = "Check();"})

this way you can populate any no of dropdowns

Thanks cnuonline,

I am already using the Viewbag, and works ok, but I got confused, I’m still using ths class, when you say I don’t have to write a class, how do I convert the datatable to List if I am not using an object with the defined properties?

to populate selectlist by iterating through data table  rows.

DataTable dt=new DataTable();
SelectListItem[] items = new SelectListItem[dt.Rows.Count];
foreach (DataRow dr in dt.Rows)
{
    SelectListItem item = new SelectListItem { Text = dr["name"].ToString(), Value = dr["id"].ToString() };
    items.ad(item);
}
ViewBag.DDList = new SelectList(items, dataValueField : "Value", dataTextField : "Text");

Leave a Reply