For a Dropdown (as a SelectList) in my View, I can successfully set the value to the Id returned by my model, but the list does not update to reflect the selected Id as the selected item.
<%var type = Model.CompanyTypeId; %>
<%= Html.DropDownList("Type", (ViewData["Types"] as SelectList),
new Dictionary<string, object>()
{
{ "class", "form-control form-input"},
{ "Id", "CoType"},
{ "Name", "CoType"},
{ "value", type },
{ "option", "selected" }
})%>
I expect the dropdown list to update the selected item to the corresponding Id
(In ChromeDev tools I can verify the Id=Model.CompanyTypeId and option="selected", but the dropdown list still shows the item selected by default.
I expect the dropdown list to update the selected item to the corresponding Id
(In ChromeDev tools I can verify the Id=Model.CompanyTypeId and option="selected", but the dropdown list still shows the item selected by default.
<select id="CoType" name="CoType" class="form-control form-input"
option="selected" value="1">
<option value="-1">- Assign Type - </option>
<option value="1">Dummy</option>
<option value="2">Test CompanyType</option>
</select>
Since you already have Model.CompanyTypeId
, you can easily use Html.DropDownListFor
. You don't set value on the HTML attributes.
Controller
public ActionResult Index()
{
var model = new TestModel
{
CompanyTypeId = 1
};
ViewBag.Types = new List<SelectListItem>
{
new SelectListItem { Value = "-1", Text = "-- Assign Type --" },
new SelectListItem { Value = "1", Text = "Dummy" },
new SelectListItem { Value = "2", Text = "Test" },
};
return View(model);
}
View
@Html.DropDownListFor(m => m.CompanyTypeId,
(ViewBag.Types as List<SelectListItem>),
new Dictionary<string, object>()
{
{ "class", "form-control form-input"},
{ "Id", "CoType"},
{ "Name", "CoType"}
})