a developer's notes – a semi-technical web development BLOG

August 27, 2013

ASP.NET MVC Html.DropDownList and Html.DropDownListFor Examples

Html.DropDownList (Webforms Snytax)

View Model:

public class ViewModel
{
	public List<SelectListItem> MyList { get; set; }
}

Controller:


public ActionResult Index()
{
	var model = new ViewModel();            
	GetMyList(model);
	ViewData.Model = model;
	return PartialView("Index");
}

private void GetMyList(ViewModel model)
{
	var cars = (from d in this.Repository.Cars
				 where d.Id == User.Id
				 select d).ToList();
				 
	var listItems = new List<SelectListItem>();
	listItems.Add(new SelectListItem { Text = "-Select Item-", Value = "-1", Selected = true });
	listItems.AddRange(from d in cars
					 select new SelectListItem
					 {
						 Text = d.Desc,
						 Value = d.ID.ToString(),
						 Selected = false
					 });
													 
													 
	model.MyList = listItems;
}

View:

<%= Html.DropDownList("itemsDdlName", Model.MyList , null, null})%>

Html.DropDownListFor (Razor)

View Model:

public class ViewModel
{
	public List<City> Cities { get; set; } 
    public int? CityId { get; set; }
    public List<City> Cities { get; set; }   
}

public class City
{
	public int CityId { get; set; }
	public string CityDescription { get; set; }
}

Controller:


public ActionResult Index()
{
    var model = new ViewModel();           
    GetCities(model);
    ViewData.Model = model;
    return PartialView("Index");
}

private void GetCities(ViewModel m)
{
	using (var db = new CityEntities())
	{
		m.Cities = db.Cities.ToList();
	}
}

View:

@Html.DropDownListFor(model => model.CityId, Model.Cities.ToSelectListItems(x => x.CityDescription, x => x.CityId.ToString(), x => x.CityId == Model.CityId))
Advertisements

1 Comment »

  1. I’ve read a few of these but each had some other twist/option/pattern they were trying to show that obfuscated the solution to my issue. Thankfully, yours did not. +1 for you.

    Comment by Gord Cross — October 14, 2016 @ 2:23 pm | Reply


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: