Created
April 2, 2015 03:22
-
-
Save csharpforevermore/06f82d45b717002ca5f1 to your computer and use it in GitHub Desktop.
MVC 4 SelectList example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Category | |
{ | |
public int ID { get; set; } | |
public string Name { get; set; } | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@{ | |
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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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