I have a dropdownlist is set to '--Select Item--' when the form is loaded first time. I don't see the Selected Item getting selected after I submit the for开发者_C百科m. It is set to '--Selected Item--' again. What could be the problem?
<%= Html.DropDownList("lstDetails", new SelectList((IEnumerable)ViewData["DetailList"], "ID", "Details"), "--Select Item--")%>
Thanks..
I assume you wish to save the selected item somewhere.
<%: Html.DropDownFor(selectedId, new SelectList((IEnumerable)ViewData["DetailList"], "ID", "Details", (IEnumerable)ViewData["DetailList"].FirstOrDefulft(x => x.Id == selectedId), "--SelectItem--") %>
You need to store the information which item was selected. I used here an int called
int selectedId
I assumed you have a Id field in your detailList items.
The easiest way is to put SelectList in the model. (Just make sure you are creating the SelectList in the constructor of the model).
View:
<%= Html.DropDownList("lstDetails", Model.DetailList)%>
Controller:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult MyController(MyModel model)
{
return View(model);
}
Model:
class MyModel
{
public SelectList DetailList;
public MyModel()
{
DetailList = new SelectList(....
}
}
So after you post back, if you return the view with the same model then the form will look the same as before you submitted the form.
精彩评论