Reputation: 203
I am succesfullly able to save value to database (title value) on insert , but when i render the same view in edit mode then title field must hold the selected value but in my case no value is selected by title dropdown...dont know why i am getting a dropdown with nothing selected while title field holds the stored value(at backend).
@Html.DropDownListFor(model => model.title, new SelectList(Model.titles, "Value", "Text"),"-Select-") // nothing selected on edit mode
@Model.title //displaying the stored value which the user selected initially.
values for title
titles = new SelectList(ListItem.getValues().ToList(), "Value", "Text").ToList();
getValue function
public static List<TextValue> getValues()
{
List<TextValue> titles= new List<TextValue>();
TextValue T= new TextValue();
T.Value = "Mr";
T.Text = "Mr";
titles.Add(T);
T= new TextValue();
T.Value = "Mrs";
T.Text ="Mrs";
titles.Add(T);
T= new TextValue();
T.Value = "Miss";
T.Text = "Miss";
titles.Add(T);
T= new TextValue();
T.Value ="Other";
T.Text = "Other";
titles.Add(T);
return titles;
}
Upvotes: 5
Views: 2802
Reputation: 60493
You've got to use another ctor of SelectList
From msdn
SelectList(IEnumerable, String, String, Object)
Initializes a new instance of the SelectList class by using the specified items for the list, the data value field, the data text field, and a selected value.
Then :
@Html.DropDownListFor(model => model.title,
new SelectList(Model.titles, "Value", "Text", Model.title),
"-Select-")
By the way, it's generally a good idea to follow basics standards (at least) : your properties should begin by an Upper case char.
public string Title {get;set;}
Upvotes: 3
Reputation: 594
Views:
@Html.DropDownListFor(model => model.title, Model.titles, "-Select-")
Controllers:
Model.titles = new SelectList(ListItem.getValues(), "Value", "Text");
public static List<SelectListItem> getValues()
{
List<SelectListItem> titles= new List<SelectListItem>();
SelectListItem T= new SelectListItem();
T.Value = "Mr";
T.Text = "Mr";
titles.Add(T);
T = new SelectListItem();
T.Value = "Mrs";
T.Text = "Mrs";
titles.Add(T);
T = new SelectListItem();
T.Value = "Miss";
T.Text = "Miss";
titles.Add(T);
T = new SelectListItem();
T.Value = "Other";
T.Text = "Other";
titles.Add(T);
return titles;
}
public ActionResult Edit(int sno)
{
var model = db.table.SingleOrDefault(x => x.sno == sno);
return View(model);
}
Upvotes: 0