Html.DropDownList For value not selected in edit mode

I successfully save the value for the database (header value) when pasting, but when I render the same view in edit mode, then the header field should contain the selected value, but in my case no value is selected from the drop-down list .. dont I know why I get a drop-down list with nothing selected, while the header field contains the saved value (on the 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 the header

 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; } 
+4
source share
2 answers

You must use another ctor SelectList

From msdn

 SelectList(IEnumerable, String, String, Object) 

Initializes a new instance of the SelectList class, using specific items for the list, data value field, data text field, and selected value .

Then:

 @Html.DropDownListFor(model => model.title, new SelectList(Model.titles, "Value", "Text", Model.title), "-Select-") 

By the way, it’s generally good to follow the basic standards (at least): your properties should start with an uppercase char.

 public string Title {get;set;} 
+2
source

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); } 
0
source

Source: https://habr.com/ru/post/1440203/


All Articles