【发布时间】:2010-06-22 16:35:27
【问题描述】:
我有一个简单的 MVC 2 博客,我正在学习它。我的编辑页面有标题、正文、日期、启用和标签。标签是我的问题所在。我有一个标签表和一个帖子表,标签通过 PostTag 表与帖子相关联。我的 linq 模型设置正确,我什至可以使用 Add HttpPost 操作。
我的问题在于编辑视图,我想在其中删除加载时 Post 对象模型上的标签,并使用 Post 对象模型上的标签更新它们(当它是 HttpPost-ed 时)。由于我的模型很复杂,我该如何做到这一点?我的编辑视图:
[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);
}
为了帮助将“编辑”页面上的标签转换为对象集合,我所做的是通过一个 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;
}
【问题讨论】:
标签: c# linq-to-sql asp.net-mvc-2