正如 Jonathan 所说,AutoMapper 将帮助您将 ViewModel 实体映射到您的域模型。这是一个例子:
在您的视图中,您使用视图模型 ( CreateGroupVM ):
@model X.X.Areas.Group.Models.CreateGroupVM
@using (Html.BeginForm(null,null, FormMethod.Post, new { @class="form-horizontal", role="form"}))
{
@Html.ValidationSummary()
@Html.AntiForgeryToken()
@Html.LabelFor(model => model.Title, new { @class = "col-lg-4 control-label" })
@Html.TextBoxFor(model => model.Title, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Title)
@Html.LabelFor(model => model.Description, new { @class = "col-lg-4 control-label" })
@Html.TextBoxFor(model => model.Description, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Description)
@Html.LabelFor(model => model.CategoryId, new { @class = "col-lg-4 control-label" })
@Html.DropDownListFor(x => x.CategoryId, Model.Categories)
@Html.ValidationMessageFor(model => model.CategoryId)
<div class="form-group">
<div class="col-lg-offset-4 col-lg-8">
<button type="submit" class="btn-u btn-u-blue">Create</button>
</div>
</div>
}
ViewModel (CreateGroupVM.cs):注意我们是如何传递一个类别列表的——如果你严格使用你的域模型,你就不能这样做,因为你不能在 Group 模型中传递一个类别列表。这在我们的视图中为我们提供了强类型的助手,并且没有使用 ViewBag。
public class CreateGroupVM
{
[Required]
public string Title { get; set; }
public string Description { get; set; }
[DisplayName("Category")]
public int CategoryId { get; set; }
public IEnumerable<SelectListItem> Categories { get; set; }
}
领域模型(Group.cs):
public class Group
{
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public int CategoryId { get; set; }
public int CreatorUserId { get; set; }
public bool Deleted { get; set; }
}
在您的 HttpPost 创建操作中 - 您让 AutoMapper 进行映射,然后保存到数据库。请注意,默认情况下 AutoMapper 将映射同名的字段。您可以阅读https://github.com/AutoMapper/AutoMapper/wiki/Getting-started以开始使用 AutoMapper。
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(CreateGroupVM vm)
{
if (ModelState.IsValid)
{
var group = new InterestGroup();
Mapper.Map(vm, group); // Let AutoMapper do the work
db.Groups.Add(group);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(vm);
}