views:

86

answers:

1

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
I have an empty constructor for Genre.
jean27
Thanks! You just gave me a very bright idea.
jean27
@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
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
Updated as per RM's comment.
Baddie