ChrisP
ChrisP

Reputation: 10116

How to get Html.DropDownList() to retain selected value on postback?

A select element is generated using the following code in an MVC4 view

@Html.DropDownList(
"abPrintYearsMode",
new List<SelectListItem>{
  new SelectListItem { Text = "Lifetime", Value = "1" },
  new SelectListItem { Text = "Manual", Value = "2" }
},
new { @class = "required" }
)

which renders the following HTML

<select class="required" id="abPrintYearsMode" name="abPrintYearsMode">
  <option value="1">Lifetime</option>
  <option value="2">Manual</option>
</select>

How do I get the select element to retain the value selected by the user on a postback? Currently, the topmost option "Lifetime" is always selected after a postback even when the user select "Manual" option #2.

Upvotes: 1

Views: 2100

Answers (3)

Janie B
Janie B

Reputation: 313

try

@Html.DropDownListFor( x => x.abPrintYearsMode,
new List<SelectListItem>{
  new SelectListItem { Text = "Lifetime", Value = "1" },
  new SelectListItem { Text = "Manual", Value = "2" }
},
new { @class = "required", id= "abPrintYearsMode"}
)

Upvotes: 2

Dmitry Efimenko
Dmitry Efimenko

Reputation: 11203

You need a property on the model that is used by the view that will contain the selected value of the dropdown. It appears in your case this property needs to be:

public int abPrintYearsMode { get; set; }

Upvotes: 0

sanvj
sanvj

Reputation: 147

Have you tried setting autopostback property to true?

Dropdown Box has the property autopostback whcih if set to true fires an event. So when ever user selects a different value in the combo box, an event will be fired in the server. i.e. a request will be send to the server

Reference

Upvotes: 0

Related Questions