2

asp.net mvc 4、实体框架 5、SQL Server 2012 Express

我有一个地方模型:

public virtual int PlaceID { get; set; }
public virtual ICollection<Tag> Tags { get; set; }
public virtual string Name { get; set; }

和相关的标签模型:

public virtual int TagID { get; set; }
public virtual string Name { get; set; }
public virtual string NamePlural { get; set; }
public virtual ICollection<Place> Places { get; set; }

多对多的关系。

有一个与以下 ViewModel 关联的视图。在其中我可以编辑地点详细信息 - 并编辑与该地点相关联的标签(例如,该地点可能有一个“餐厅”标签和一个“酒吧”标签 - 也许我想添加一个“咖啡馆”标签,并且删除“餐厅”标签)。

PlacesWithTagsViewModel:

public Place place { get; set; }
public ICollection<Tag> SelectedTags { get; set; }

当视图将 httpost 返回到控制器时 - 我更新标签如下:

place.Tags = SelectedTags
db.Entry(ptvm.place).State = EntityState.Modified;
db.SaveChanges();

然而,地方属性更新(例如名称) - 但标签始终保持不变。

如何更新标签?

4

1 回答 1

0

Avoid db.Entry(ptvm.place).State = EntityState.Modified; as it causes conflicts with no updation.

You must use UpdateModel(table object, "model");

Full Example is as belows :

[HttpPost]
public ActionResult PlaceTag(PlacesWithTagsViewModel model)
{
    if (ModelState.IsValid)
    {
       tag tagtest = GetTagById(model.tagid);
       tag.name= model.tag.name;
       tag.nameplural = model.tag.nameplural;
       UpdateModel(tag, "model");
       db.SaveChanges();
       return RedirectToAction("Index", "Dashboard", new { id = 5 });
    } 
}

The advantage of UpdateModel is that you have to mention only those fields which you update avoiding those which remain static. In this way you can update your related data with Viewmodel in Edit View.

于 2013-06-05T10:17:19.303 回答