使用Automapper编辑模型MVC4的选定字段

时间:2013-07-24 19:26:01

标签: asp.net-mvc-4 automapper asp.net-mvc-viewmodel

我正在尝试使用原始模型(OApply)的viewmodel(OApplyIDViewModel)更新所选字段。当我运行时,更改不受影响。我将感谢任何有经验的人的帮助。我没有得到任何错误。表单提交并重定向。

我在global.asax

有这个
   AutoMapper.Mapper.CreateMap<OApplyIDViewModel, OApply>();

这是ViewModel

 public class OApplyIDViewModel
{
    [Key]
public int OAId { get; set; }

[Display(Name = "Identification")]
[Required(ErrorMessage = "Identification Required")]
public int IdId { get; set; }

[Display(Name = "Identification Number")][Required(ErrorMessage="ID Number Required")]
public string AIdentificationNo { get; set; }

[Display(Name = "Licence Version(5b)")]
[RequiredIf("IdId", Comparison.IsEqualTo, 1, ErrorMessage = "Version(5b) Required")]
public string ALicenceVersion { get; set; }

   public int CountryId { get; set; }
    [RequiredIf("IdId",Comparison.IsNotEqualTo,1, ErrorMessage="Country Required")]

    [Display(Name = "Your Electronic Signature Date Seal")]
    [Required(ErrorMessage="Date Signature Seal Required")]
    public DateTime SigDate { get; set; }
    [ScaffoldColumn(false)]
    [Display(Name = "Last Updated on")]
    public DateTime UDate { get; set; }
    [ScaffoldColumn(false)]
    [Display(Name = "Last Updated by")]
    public String UDateBy { get; set; }
    }

这是在控制器

// GET

     public ActionResult  ClientEditID(int id)
    {
     var model = new OApplyIDViewModel();
     OApply oapply  = db.OApply.Find(id);
    if (model == null )
     {

         return HttpNotFound();
     }
     ViewBag.CountryId = new SelectList(db.Countries, "CountryId", "CountryName", model.CountryId);
     ViewBag.IdId = new SelectList(db.PhotoIds, "IdId", "IdName",  model.IdId);
     return View();
      } 


[HttpPost]
   public ActionResult ClientEditId(OApplyIDViewModel oapply, int Id)
    {
   if (!ModelState.IsValid)
     {
    return View(oapply);
     }

    var onlineid = db.OApply.Where(x => x.OAId == Id).FirstOrDefault();
    Mapper.Map<OApplyIDViewModel,OApply>(oapply);
     oapply.UDateBy = Membership.GetUser().ProviderUserKey.ToString();
     oapply.UDate = DateTime.Now;
     db.Entry(onlineid).State= EntityState.Modified;
     db.SaveChanges();
     ViewBag.CountryId = new SelectList(db.Countries, "CountryId", "CountryName", oapply.CountryId);
     ViewBag.IdId = new SelectList(db.PhotoIds, "IdId", "IdName", oapply.IdId);
     return RedirectToAction("HomeAccount");

}

这是视图

   @using (Html.BeginForm("ClientEditId", "OApply", FormMethod.Post, new { enctype = "multipart/form-data", @class = "stdform" }))
  {
    @Html.ValidationSummary(true)
      <fieldset>
    <legend>OnlineApplication</legend>
      @Html.HiddenFor(model => model.OAId)

    <div class="related">
    <div class="editor-label">
        @Html.LabelFor(model => model.IdId, "IdType")
    </div>
    <div class="editor-field">
        @Html.DropDownList("IdId", String.Empty)
        @Html.ValidationMessageFor(model => model.IdId)
    </div>
    <div class="editor-label">
        @Html.LabelFor(model => model.AIdentificationNo)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.AIdentificationNo)
        @Html.ValidationMessageFor(model => model.AIdentificationNo)
    </div>

    <div class="requiredfields">
    <div class="editor-label">
        @Html.LabelFor(model => model.ALicenceVersion)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.ALicenceVersion)
        @Html.ValidationMessageFor(model => model.ALicenceVersion)
    </div>
    </div>
    <div class="country">
     <div class="editor-label">
        @Html.LabelFor(model => model.CountryId)
    </div>
    <div class="editor-field">
        @Html.DropDownList("CountryId")
        @Html.ValidationMessageFor(model => model.CountryId)
    </div>
    </div></div>
      <div class="editor-label">
        @Html.LabelFor(model => model.SigDate)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.SigDate)
        @Html.ValidationMessageFor(model => model.SigDate)
    </div>

    <p>
        <input type="submit" value="Save" />
    </p>

1 个答案:

答案 0 :(得分:0)

这里有问题:

    var onlineid = db.OApply.Where(x => x.OAId == Id).FirstOrDefault();
->  Mapper.Map<OApplyIDViewModel,OApply>(oapply);
    oapply.UDateBy = Membership.GetUser().ProviderUserKey.ToString();
    oapply.UDate = DateTime.Now;
    db.Entry(onlineid).State= EntityState.Modified;

带箭头的行返回一个新的OApply实例。它不会更新onlineid。事实上,它不知道onlineid。请尝试以下方法。

Mapper.Map<OApplyIDViewModel,OApply>(oapply, onlineid);

现在它将修改onlineid而不是返回一个。但是,如果主键是identity(自动递增),则应忽略主键的映射。

AutoMapper.Mapper.CreateMap<OApplyIDViewModel, OApply>()
    .ForMember(dest => dest.OAId, opt => opt.Ignore());

我不确定OAId是否是您的主键。您根本不遵循命名约定,也可能不遵循其他约定。


我已对您的代码进行了更正:

public ActionResult  ClientEditID(int id)
{
 OApply oapply  = db.OApply.Find(id);

->if (oapply == null )
 {
     return HttpNotFound();
 }
->var model = Mapper.Map<OApply, OApplyIDViewModel>(oapply); 

 ViewBag.CountryId = new SelectList(db.Countries, "CountryId", "CountryName", model.CountryId);
 ViewBag.IdId = new SelectList(db.PhotoIds, "IdId", "IdName",  model.IdId);

->return View(model);
  } 

您的HttpPost大部分有效,只是您在使用ViewBag之前将数据放入RedirectToAction()。那些数据将会丢失。相反,请使用TempData字典。检查msdn。