views:

2521

answers:

1

Hi,

I have an ASP.NET MVC view which contains checkboxes for user-defined categories.

<td><% foreach (Category c in (List<Category>)ViewData["cats"]) {
       if (selCats.ContainsKey(c.ID)) { %>
       <input name="CategoryIDs" type="checkbox" value="<%=c.ID %>" checked="checked" />&nbsp;<%= c.Name%><% } 
        else { %>
       <input name="CategoryIDs" type="checkbox" value="<%=c.ID %>" />&nbsp;<%= c.Name%> <% } %>
     <% } %>
</td>

The form is posted to the following controller action:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, int [] CategoryIDs)
{
    PostsDataContext db = new PostsDataContext();
    var post = db.Posts.Single(p => p.ID == id);
    UpdateModel(post, new[] { "Title", "Subtitle", "RawContent", "PublishDate", "Slug" });
    db.SubmitChanges();
    return Redirect("/archives/" + post.Slug);
}

The form checkboxes will be converted to an array of integer IDs "CategoryIDs", each representing a selected category. I then want to put these into a association table containing two columns: PostID and CategoryID. This is used to set up a many-to-many association between Posts and Categories.

Currently I am brute-forcing it: looping through the categories, and for each one, adding a row to the association table containing the category ID, and the ID of the post to which it belong.

But I'm wondering if there's a cleaner way to do this automagically in the context of ASP.NET MVC and LINQ to SQL?

Thanks!

+7  A: 

I think what you're doing is fine... the only thing I would say is that if you don't want to loop through the ID's, you could add them at the same time with "InsertAllOnSubmit" (even though this is really just looping too):

int[] categoryIDs = new int[] { 0, 1, 2 };

dataContext.PostCategories.InsertAllOnSubmit(
categoryIDs.Select(id =>
 new PostCategory
 {
  CategoryID = id,
  PostID = myPostID
 })
);

But either way, that's still just doing the same as what you have.

Timothy Khouri