i have form in asp.net mvc that retrieves records from database.this form have dropdowns. in Edit action of controller it is must to have selected the already inserted items. suppose if i am taking the User information for edit, then its City,State and country开发者_如何转开发 must be selected as they inserted before.Can any one tell me how to set values from database as selected in drop down list when page loads???
Assuming you have a user model with State as property you need to do the following for your view
<div class="editor-field">
@Html.DropDownListFor(model => model.State, (SelectList)ViewBag.StateDDL)
@Html.ValidationMessageFor(model => model.State)
</div>
here is the code for the controller
public ActionResult Edit(string id)
{
UserModel myuser = new UserModel();
Get the user data from database here
myuser.State = "AZ";
List<SelectListItem> mystate= new List<SelectListItem>();
SelectListItem item = new SelectListItem();
item.Text = " - SELECT - ";
item.Value = "";
mystate.Add(item);
item = new SelectListItem();
item.Text = "CA";
item.Value = "CA";
mystate.Add(item);
item = new SelectListItem();
item.Text = "AZ";
item.Value = "Az";
mystate.Add(item);
ViewBag.StateDDL = new SelectList(mystate.AsEnumerable(), "Value", "Text", myuser .State);
return View(myuser);
}
精彩评论