![](/img/trans.png)
[英]Using AutoMapper to map complex viewmodel back to model with collection property
[英]How to map back ViewModel to Model (MVC EF)
在mvc asp.net中,有數十種解決方案如何將模型映射到視圖模型,例如automapper或valueinjecter。 但是,我只是不知道如何映射回去。 一個簡單的例子
我這里有一個像這樣的復雜模型
public class Address
{
public int AddressID { get; set; }
public string OwnerID { get; set; }
public virtual ApplicationUser Owner { get; set; }
public String Name { get; set; }
public String Street { get; set; }
public int ZipCode { get; set; }
public String City { get; set; }
public string Email { get; set; }
// fancy business logic stuff like
public Nullable<Guid> requestCode { get; set; }
// or even this
public string BestFriendID { get; set; }
public virtual ApplicationUser BestFriend{ get; set; }
public virtual ICollection<OtherModel> Mycollection { get; set; }
// And some enums
public MyEnum MyEnum { get; set; }
}
但是在一種情況下,我只想編輯此地址的名稱和電子郵件,所以我繼續為其創建一個視圖模型
public class SimpleEmailEditVM
{
[MyDataAnnotations]
public String Name { get; set; }
[MyDataAnnotations]
public String Email { get; set; }
}
這樣可以創建一個非常簡單的視圖
@model project.ViewModels.SimpleEmailEditVM
@Html.EditorFor(model => model, new { htmlAttributes = new { @class = "form-control" } })
並且我可以將viewmodel(例如Street
添加為字段,而無需更新View。 從模型到視圖模型的映射可以使用valueinjecter輕松完成,但是現在我的問題是:如何映射回去?
在viewmodel中沒有ID信息,那么如何找到正確的模型(我可以想象,具有相同名稱和電子郵件但ID完全不同的多個條目)? 控制器的外觀如何?
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind] SimpleEmailEditVM vm)
{
if (ModelState.IsValid)
{
/* find the correct address from db and update the
fields specified in the viewmodel? */
db.Entry(address).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(address);
}
我能想到的一種解決方案是添加Id並將其隱藏( 如此處所示 )。 這是正確且唯一的方法嗎? 這里的問題是,我的ID被傳遞了,我可以想象這不是將內部ID傳遞給用戶的很好的做法。
我可以想象這不是將內部ID傳遞給用戶的很好的做法。
公開ID本身並不是問題,除非該ID是敏感數據(例如SSN)。 此問題的ID在網址中公開。 您的用戶ID顯示在您的個人資料中。
訣竅是確保當ID返回時,您可以檢查其有效性並檢查允許執行該操作的身份來執行該操作。 這可能是角色或權限檢查,或者可能需要在記錄級別進行細化。
這是一些偽代碼來證明這一點。
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind] SimpleEmailEditVM vm)
{
var itemToEdit = db.Find(vm.Id);
//Make sure Id is valid
if(itemToEdit == null) return BadRequest();
//Make sure user can edit this object
if(!User.IsInRole("CanEditItems")) return Forbidden();
if(itemToEdit.AllowedUser != User.Identity.Name) return Forbidden();
if (ModelState.IsValid)
{
/* find the correct address from db and update the
fields specified in the viewmodel? */
db.Entry(address).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(address);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.