Created
September 1, 2015 17:16
-
-
Save jburditt/397f42f1e5d245ccedc3 to your computer and use it in GitHub Desktop.
MVC Checkboxes
This file contains 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
/* | |
Here’s a neat nuget for packing lists of checkboxes based on a MVC model. Currently implementing this for activities on the signup form. | |
http://www.codeproject.com/Tips/613785/How-to-Use-CheckBoxListFor-With-ASP-NET-MVC | |
note, as shown below, you do actually need to get the list of available ones twice. | |
There is also relatively new to .net html.enumdropdownlist for. I think I will implement this for the gender selection. | |
https://msdn.microsoft.com/en-us/library/system.web.mvc.html.selectextensions.enumdropdownlistfor(v=vs.118).aspx | |
*/ | |
/// <summary> | |
/// for get all fruits | |
/// </summary> | |
[HttpGet] | |
public ActionResult Index() | |
{ | |
return View(GetFruitsInitialModel()); | |
} | |
/// <summary> | |
/// for post user selected fruits | |
/// </summary> | |
[HttpPost] | |
public ActionResult Index(PostedFruits postedFruits) | |
{ | |
return View(GetFruitsModel(postedFruits)); | |
} | |
private FruitViewModel GetFruitsModel(PostedFruits postedFruits) | |
{ | |
// setup properties | |
var model = new FruitViewModel(); | |
var selectedFruits = new List<Fruit>(); | |
var postedFruitIds = new string[0]; | |
if (postedFruits == null) postedFruits = new PostedFruits(); | |
// if a view model array of posted fruits ids exists | |
// and is not empty,save selected ids | |
if (postedFruits.FruitIds != null && postedFruits.FruitIds.Any()) | |
{ | |
postedFruitIds = postedFruits.FruitIds; | |
} | |
// if there are any selected ids saved, create a list of fruits | |
if (postedFruitIds.Any()) | |
{ | |
selectedFruits = FruitRepository.GetAll() | |
.Where(x => postedFruitIds.Any(s => x.Id.ToString().Equals(s))) | |
.ToList(); | |
} | |
//setup a view model | |
model.AvailableFruits = FruitRepository.GetAll().ToList(); | |
model.SelectedFruits = selectedFruits; | |
model.PostedFruits = postedFruits; | |
return model; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment