Reputation: 2448
How to save chosen value in dropdownlist after submit. So the value that you choose in dropdownlist stays after user click on submit.
In my controller I did this:
List<SelectListItem> uraList = new List<SelectListItem>();
for (int i = 1; i < 7; i++)
{
uraList.Add(new SelectListItem
{
Value = i + ":00",
Text = i + ":00"
});
}
ViewBag.IzberiUro = uraList;
ViewBag.IzbranaUra = model.Ura;
In my Model (I think that here is mistake):
public string Ura { get; set; }
And in View I have:
@Html.DropDownList("Ura", ((IEnumerable<SelectListItem>)ViewBag.IzberiUro).Select(t => new SelectListItem() {Text = t.Text, Value = t.Text,Selected = (t.Text == ViewBag.IzbranaUra)}), new {@class = "css"})
The result is, in view I have dropdownlist with values from 1:00 to 6:00 (whitch is correct, and first choosen value is 1:00), but, when I choose e.g. 4:00 and click on submit, the value in dropdown returns to 1:00.
Realy thanks for help.
my generated HTML is then like this:
<select class="form-control" id="Ura" name="Ura" placeholder="Ura" style="width: 100px;">
<option value="1:00">1:00</option>
<option value="2:00">2:00</option>
<option value="3:00">3:00</option>
<option value="4:00">4:00</option>
<option value="5:00">5:00</option>
<option value="6:00">6:00</option>
</select>
Upvotes: 0
Views: 2051
Reputation: 24312
Use DropDownListFor
instead of DropDownList
@Html.DropDownListFor(m => m.Ura, Model.uraList)
Upvotes: 1