How to make the DropDownList selected value persist after a POST action in ASP.NET MVC 3?
I'm trying to use this DropDownList stuff for the first time, and so far, I didn't achieve my goal. My goal is to have a DDList, and after the desired value is selected, we use the onchange
event to do the post action, but after the POST action is done, the DDList resets to the first value, making impossible to select the first item.
Guys, I know there are better ways around it (like not using this onchange, or instead of a DDList using a ul or a table, but I'm trying to understand POST actions 开发者_运维技巧and DDList, in case I have to use this again.
Can you gentle guys help me out?
when loading data to the DD, you must validate first
if (!isPostBack)
fillDD();
I'm in MVC4. In case anybody else has trouble understanding here is my solution to the problem.
//Razor View
@Html.DropDownList("StateID", (SelectList)ViewBag.stateList, "--Select--")
//Code
public ActionResult Create()
{
MyOtherData d = new MyOtherData();
//Load the Dropdown here
ViewBag.stateList = new SelectList(db.State, "StateID", "Name");
return View(d);
}
[HttpPost]
//Notice the 2nd parameter StateID in Action Result must match the 4th parameter in the ViewBag SelectList Below and the first parameter in the DropDownList called StateID.
//The 4th parameter will act like the SelectedItem we were all familiar with in ASP.Net
public ActionResult Create(ModelData data, String StateID)
{
if(ModelState.IsValid)
{
//...
}
//Return SelectList to the dropdownlist here
ViewBag.stateList = new SelectList(db.State, "StateID", "Name", StateID);
return View(data);
}
精彩评论