Skip to content

Instantly share code, notes, and snippets.

@csharpforevermore
Created April 2, 2015 03:22
Show Gist options
  • Save csharpforevermore/06f82d45b717002ca5f1 to your computer and use it in GitHub Desktop.
Save csharpforevermore/06f82d45b717002ca5f1 to your computer and use it in GitHub Desktop.
MVC 4 SelectList example
public class Category
{
public int ID { get; set; }
public string Name { get; set; }
}
public class HomeController : Controller
{
private List<Category> GetOptions()
{
List<Category> categories = new List<Category>();
categories.Add(new Category() { ID = 1, Name = "Bikes" });
categories.Add(new Category() { ID = 2, Name = "Cars" });
categories.Add(new Category() { ID = 3, Name = "Trucks" });
return categories;
}
public ActionResult Index()
{
Product product = new Product();
ViewBag.Categories = GetOptions();
return View(product);
}
[HttpPost]
public ActionResult Index(Product product)
{
ViewBag.Categories = GetOptions();
return View(product);
}
}
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head runat="server">
<title>ASP.NET MVC Select List Example</title>
</head>
<body>
<div>
<h1>Select Values</h1>
<ul>
@foreach (int c in Model.CategoryID)
{
<li>@c</li>
}
</ul>
@Html.DisplayForModel()
<h1>Change Values</h1>
@using (Html.BeginForm())
{
@Html.ListBoxFor(x => x.CategoryID, new MultiSelectList(ViewBag.Categories, "ID", "Name", Model.CategoryID))
<br />
<input type="submit" value="Submit" />
}
</div>
</body>
</html>
public class Product
{
public ICollection<int> CategoryID { get; set; }
public Product()
{
CategoryID = new List<int>();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment