There's a number of questions about this on SO already and I've looked through quite a few of them, but am still unable to figure out exactly what I'm doing wrong here. I'm able to have a dropdownlistfor populate the select values without any issue, but setting the value of the list from the database isn't working.
Basically the same select list is used multiple times on the page, and there is a seperate model variable that tracks the value for each instance. Here's an example of for the hdr_base_uom variable:
The model:
public string hdr_base_uom { get; set; }
public List<UomOption> putupOptions { get; set; }
public class UomOption
{
public int uom_id { get; set; }
public string uom_description { get; set; }
}
Populating the list:
public List<UomOption> GetPutupOptions()
{
try
{
using (IfxConnection con = new IfxConnection(WebConfigurationManager.AppSettings["IBMCONN"].ToString()))
{
con.Open();
List<UomOption> uomOptions= con.Query<UomOption>("select uom_id, initcap(uom_description) as uom_description " +
" from oe_unitom " +
" where uom_group = 1 order by uom_description").ToList();
con.Close();
uomOptions.Insert(0, new UomOption(){ uom_id = 0, uom_description = " "});
return uomOptions;
}
}
catch (Exception x)
{
throw x;
}
}
The view:
@Html.DropDownListFor(model => model.hdr_base_uom, new SelectList(Model.putupOptions,
"uom_id", "uom_description", Model.hdr_base_uom),
new { disabled = "disabled", style = "width:13em" })
If I simply display the value of model.hdr_base_uom
on the page then the uom_id
that is set to that variable shows up. Attempting to use that ID to set the value of the dropdownlistfor
does nothing, however. For example if the uom_id
is 58
which has the corresponding description of "Roll"
to be displayed, instead of defaulting to Roll the dropdownlistfor
instead shows the first element in the list (the empty element added above.)
Any thoughts on what I'm doing wrong here?
I'm not sure what Model.hdr_base-uom
means. You don't need it though:
@Html.DropDownListFor(model => model.hdr_base_uom, new SelectList(Model.putupOptions,
"uom_id", "uom_description"),
new { disabled = "disabled", style = "width:13em" })
Also ensure that you set "58"
(or whatever the selected value should be, stringified) to hdr_base_uom
field.
Your example works for me as is (with or without Model.hdr_base-uom
) (in modern browsers, of course).