20131

Set the selected item in dropdownlist in MVC3

I have to set the selected item for a dropdownlist in view. But its not working.

//View

<div class="editor-label"> @Html.LabelFor(model => model.Gender) </div> <div class="editor-field"> @Html.DropDownListFor(model => model.Gender,Model.GenderList) </div>

//Model

[Required(ErrorMessage = "Please select gender!")] [Display(Name = "Gender")] public string Gender { get; set; } public IEnumerable<SelectListItem> GenderList { get { return new[] { new SelectListItem { Value = "0", Text = "Select" }, new SelectListItem { Value = "1", Text = "Male" }, new SelectListItem { Value = "2", Text = "Female" }, }; } }

The gender property has the value needs to be selected in the list. Still not working.

Where i'm wrong?

Answer1:

First, create your ViewModel.

public class MovieViewModel { public string Genre { get; set; } public IEnumerable<SelectListItem> GenreList { get { yield return new SelectListItem { Text = "Comedy", Value = "1" }; yield return new SelectListItem { Text = "Drama", Value = "2" }; yield return new SelectListItem { Text = "Documentary", Value = "3" }; } } }

Then, your controller creates a new instance of this ViewModel and sends it to the view.

public class HomeController : Controller { // // GET: /Home/ public ActionResult Index() { var viewModel = new MovieViewModel { Genre = "2" }; return View(viewModel); } }

Finally, the view displays the dropdownlist using the ASP.NET wrapper [Html.DropDownListFor()][1].

@model MvcApplication1.Models.MovieViewModel <!DOCTYPE html> <html> <head> <title>My movie</title> </head> <body> <div> @Html.DropDownListFor(m => m.Genre, Model.GenreList) </div> </body> </html>

The selected value is then automatically chosen according the ViewModel. There's no need to manually set the Selected property of the objects SelectListitem.

Answer2:

The SelectListItem type has a Selected property, you need to is to true on the item you wish to set as selected.

You can either set it statically like the following:

public IEnumerable<SelectListItem> GenderList { get { [...] new SelectListItem { Value = "0", Text = "Select", Selected = true}, [...] } }

Or enumerate over the collection for a match with Gender value:

var selected = GenderList.SingleOrDefault(item => item.Text.Equals(this.Gender)); if (selected != null) selected.Selected = true;

Recommend

  • Creating a dropdown list in MVC nhibernate
  • MVC3 - Get Data Attribute in html.helper
  • Working with EditorTemplates and radio buttons
  • Setting default value to Html.DropDownListFor
  • How can we get radio button values from form using body-parser on an expressjs server?
  • PL/SQL: re-write SELECT statement using IN parameter in stored procedure
  • Why ValidatorValidate() validates all the RequiredFieldValidator controls on the page?
  • GTK# window not rendered completely
  • Relational Database Mapping in MVC
  • Finding All Combinations (cartesian product) of list values in vb.net
  • FlexJSON Orders Alphabetically by Default
  • SQL - count occurrences of gender
  • ASP.NET RegularExpressionValidator, validate on a non-match?
  • Trying to string.Join an IList
  • Cannot get the UserManager class
  • Linq Merge lists
  • Can I display google adwords (AdView) in javafx on android
  • Validaiting emails with Net.Mail MailAddress
  • MySQL WHERE-condition in procedure ignored
  • sending/ receiving email in Java
  • ORA-29908: missing primary invocation for ancillary operator
  • Web-crawler for facebook in python
  • How to get next/previous record number?
  • AT Commands to Send SMS not working in Windows 8.1
  • Cannot Parse HTML Data Using Android / JSOUP
  • Windows forms listbox.selecteditem displaying “System.Data.DataRowView” instead of actual value
  • trying to dynamically update Highchart column chart but series undefined
  • How do you join a server to an Active Directory (domain)?
  • JTable with a ScrollPane misbehaving
  • How does Linux kernel interrupt the application?
  • apache spark aggregate function using min value
  • unknown Exception android
  • Django query for large number of relationships
  • Sorting a 2D array using the second column C++
  • Why is Django giving me: 'first_name' is an invalid keyword argument for this function?
  • How can I use `wmic` in a Windows PE script?
  • failed to connect to specific WiFi in android programmatically
  • java string with new operator and a literal
  • How to push additional view controllers onto NavigationController but keep the TabBar?
  • How can I use threading to 'tick' a timer to be accessed by other threads?