There are a group of entities named Book and Magazine which inherits from the abstract class PublishedItem. PublishedItem have these properties: ID, Name, Publisher, List of Authors, List of Genres. The Book entity has the ISBN property and the Magazine entity has the ISSN property. I just want to ask how I can update the book's or magazine's list of genres if I am using a group of checkboxes for these genres?
+3
A:
ASP.NET MVC actions accept arrays as parameters.
[HttpPost]
public ActionResult EditGenres(string[] genres, int ID)
{
PublishedItem item = GetPublishedItemByID(ID);
item.Genres = genres.Select(x=> new Genre{ Name = x}); // this LINQ query just projects each string into a new genre. You can use w/e method you want to manipulate this string array into genres.
return RedirectToAction("Success");
}
To populate the array, just use the same value for the name
attribute on the form field.
<% Html.BeingForm() %>
<input type="checkbox" value="Genre1" name="genres">
<input type="checkbox" value="Genre2" name="genres">
<input type="checkbox" value="Genre3" name="genres">
<input type="checkbox" value="Genre4" name="genres">
<input type="hidden" value="1" name="ID" />
<input type="Submit" value="Submit Generes">
<% Html.EndForm() %>
Baddie
2010-04-14 03:43:44
I have an empty constructor for Genre.
jean27
2010-04-14 03:57:20
Thanks! You just gave me a very bright idea.
jean27
2010-04-14 04:00:48
@jean27 - "I have an empty constructor for Genre" - I'm sure you can work it out from this post, add a partial class to define the constructor, set using new Genre() { Name = x }, even worst case use a foreach loop of each genere in genres array and add it to the item.Generes collection.
RM
2010-04-14 04:05:00
I used the genre's ID for the checkbox value and I just searched for the genre with the ID and added it to the book/magazine.
jean27
2010-04-14 04:15:09
Updated as per RM's comment.
Baddie
2010-04-14 04:18:40