ASP.NET MVC:获取表单复选框到许多对多数据库assoc命令表的LINQ to SQL的最好方法?表单、复选框、命令、方法

2023-09-03 08:56:00 作者:再见了我的宠爱

我有一个ASP.NET MVC视图包含复选框用户定义的类别。

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);
}

的形式复选框将被转换为整数IDCategoryIDs,每个重新presenting所选类型的阵列。然后,我希望把这些到含有两列的关联表:PostID和类别ID。这是用来设置职位和类别之间的许多一对多的关联。

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.

目前,我蛮力迫使它:通过循环的类别,并为每个人,增加了行协会表包含的类别ID和的职位,它所属的ID

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.

但我不知道是否有一个更清洁的方式,自动将为此在ASP.NET MVC和LINQ的背景下,以SQL?

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?

谢谢!

推荐答案

我觉得你在做什么是好的......我要说的唯一的事情是,如果你不通过ID的要循环,你

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.