Note that there are some explanatory texts on larger screens.

plurals
  1. POASP.NET MVC: Best way to get form checkboxes into many-to-many DB assoc table with LINQ To SQL?
    primarykey
    data
    text
    <p>I have an ASP.NET MVC view which contains checkboxes for user-defined categories.</p> <pre><code>&lt;td&gt;&lt;% foreach (Category c in (List&lt;Category&gt;)ViewData["cats"]) { if (selCats.ContainsKey(c.ID)) { %&gt; &lt;input name="CategoryIDs" type="checkbox" value="&lt;%=c.ID %&gt;" checked="checked" /&gt;&amp;nbsp;&lt;%= c.Name%&gt;&lt;% } else { %&gt; &lt;input name="CategoryIDs" type="checkbox" value="&lt;%=c.ID %&gt;" /&gt;&amp;nbsp;&lt;%= c.Name%&gt; &lt;% } %&gt; &lt;% } %&gt; &lt;/td&gt; </code></pre> <p>The form is posted to the following controller action:</p> <pre><code>[AcceptVerbs(HttpVerbs.Post)] public ActionResult Edit(int id, int [] CategoryIDs) { PostsDataContext db = new PostsDataContext(); var post = db.Posts.Single(p =&gt; p.ID == id); UpdateModel(post, new[] { "Title", "Subtitle", "RawContent", "PublishDate", "Slug" }); db.SubmitChanges(); return Redirect("/archives/" + post.Slug); } </code></pre> <p>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.</p> <p>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.</p> <p>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?</p> <p>Thanks!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload