对于下面的附加示例,如何正确保存更新的模型?我害怕一些疯狂的东西,比如自定义模型绑定等。我想优雅地解决这个问题。
模型
public class Artist {
public int ArtistId { get; set; }
public string ArtistName { get; set; }
public virtual ICollection<Album> ArtistAlbums { get; set; }
}
public class Album {
public int AlbumId { get; set; }
public string AlbumName { get; set; }
}
来自创建视图的片段
<input type="text" name="ArtistAlbums" />
<input type="text" name="ArtistAlbums" />
这是创建操作
public ActionResult Create(Artist newArtist, IEnumerable<string> ArtistAlbums) {
foreach (var album in ArtistAlbums) {
newArtist.ArtistAlbums.Add(new Album { AlbumName = album });
}
db.Entry(newArtist).State = EntityState.Added;
db.SaveChanges();
return RedirectToAction("Index");
}
这是我的编辑视图
@foreach (var album in Model.ArtistAlbums) {
<div>@album.AlbumName</div>
<input type="text" name="ArtistAlbums" />
}
这是我的编辑操作
[HttpPost]
public ActionResult Edit(Artist artist, IEnumerable<string> ArtistAlbums) {
foreach (var album in ArtistAlbums) {
artist.ArtistAlbums.Add(new Album { AlbumName = album });
}
// An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
//db.Entry(artist).State = EntityState.Modified;
// this one update my Artist entry, but not my Albums for this entry.
// var oldArtist = db.Artists.Find(artist.ArtistId);
// db.Entry(oldArtist).CurrentValues.SetValues(artist);
db.SaveChanges();
return RedirectToAction("Index");
}