HttpPost用于在编辑页面中使用子项更新我的模型的操作

时间:2010-06-22 05:14:09

标签: c# linq-to-sql asp.net-mvc-2

我有一个简单的MVC 2博客,我正在学习。我的编辑页面包含标题,正文,日期,启用和标签。标签是我的问题所在。我有一个Tags表和一个Posts表,标签通过PostTag表与帖子相关联。我正确地设置了linq模型,甚至还有Add HttpPost动作。

我的问题在于编辑视图,我想在加载时删除Post对象模型上的标记,并在它是HttpPost-ed时使用Post对象模型上的标记更新它们。我怎么能完成这个,因为我的模型很复杂?我的编辑视图:

[HttpPost, Authorize, ValidateInput(false)]
public ActionResult Edit(int id, FormCollection form)
{
    Post p = repo.GetPost(id);

    if (p == null)
        return View("NotFound");

    if (ModelState.IsValid)
    {
        try
        {
            UpdateModel(p);

            //Do something here to update the model p.TagList child model
            // the p.TagList object is not updated through UpdateModel

            repo.Save();

            return RedirectToAction("Post", "Blog", new { id = p.PostID });
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.Message);
            ModelState.AddRuleViolations(p.GetRuleViolations());
        }
    }
    return View(p);
}

我帮助将Edit页面上的标签翻译成对象集合是通过TagListString对象完成的,该对象仅序列化由空格分隔的每个标记名称。当我发回它时,我可以通过迭代我的TagListString轻松地重建TagList对象 - 但它没有得到更新!

我尝试了几种更新TagList模型的方法。循环并对现有的repo.Delete()进行循环,然后添加然后重新构建并添加新的。我试过创建一个新的集合并以这种方式添加新的Tag对象。以下是我尝试过的一些事情。

public void UpdateTagList(System.Data.Linq.EntitySet<PostTag> postTags, string tagListString)
{
    db.PostTags.DeleteAllOnSubmit(postTags);
    db.PostTags.InsertAllOnSubmit(GenerateTagListFromString(tagListString, postTags.SingleOrDefault().Post));
}

private System.Data.Linq.EntitySet<PostTag> GenerateTagListFromString(string tagListString, Post post)
{
    System.Data.Linq.EntitySet<PostTag> tagList = new System.Data.Linq.EntitySet<PostTag>();

    foreach (var t in tagListString.Trim().Split(' '))
    {
        //look for this tag name in cache (MvcApplication.AllTags)
        Tag found = MvcApplication.AllTags.SingleOrDefault(item => item.TagName.Trim().ToLower() == t.Trim().ToLower());

        //new PostTag for this new Post
        PostTag pt = new PostTag();
        pt.Tag = found ?? new Tag() { TagName = t };
        pt.Post = post;

        tagList.Add(pt);
    }
    return tagList;
}

1 个答案:

答案 0 :(得分:0)

首先,我建议您使用自定义ModelBinder处理所有表单数据,这样您的控制器操作就会收到一个带有更新的标量数据和正确标签的“Post”对象,而不是接收FormCollection。

然后,解决方案略有不同,具体取决于您使用带有EF 1.0的.net 3.5或带有EF 4.0的.net 4.0。

您能提供这些信息,以便我可以进一步帮助您吗?感谢。