ASP.NET MVC3自动映射器Viewmodel/Model视图验证

5
(再次,一个MVC验证问题。我知道,我知道...)
我想使用AutoMapper(http://automapper.codeplex.com/)来验证在我的创建视图中的字段,这些字段不在我的数据库中(因此不在我的数据模型中)。
例如:我有一个Account/Create视图,用户可以创建一个新帐户,我想要一个密码和确认密码字段,以便用户必须输入他们的密码两次进行确认。
数据库中的Account表如下所示:
Account[Id(PK), Name, Password, Email]

我已经生成了一个 ADO.NET 实体数据模型,然后使用 ADO.NET 自跟踪实体生成器生成了模型。
我还编写了一个自定义的 AccountViewModel 用于验证注释,例如 [Required]。
因此,总结一下,这是我的项目结构:
Controllers:
   AccountController

Models:
   Database.edmx (auto-generated from database)
   Model.Context.tt (auto-generated from edmx)
   Model.tt (auto-generated from edmx)
   AccountViewModel.cs

Views:
   Account
      Create.cshtml

我的AccountViewModel代码如下:

public class AccountViewModel
    {
        public int Id { get; set; }

        [Required]
        public string Name { get; set; }

        [Required]
        public string Password { get; set; }

        [Required]
        [Compare("Password")]
        public string ConfirmPassword { get; set; }
    }

现在,我的创建视图看起来像这样:
@model AutoMapperTest.Models.Account
<script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Account</legend>
        <div class="editor-label">
            Name
        </div>
        <div class="editor-field">
            @Html.TextBox("Name")
            @Html.ValidationMessageFor(model => model.Name)
        </div>
        <div class="editor-label">
            Email
        </div>
        <div class="editor-field">
            @Html.TextBox("Email")
            @Html.ValidationMessageFor(model => model.Email)
        </div>
        <div class="editor-label">
            Password
        </div>
        <div class="editor-field">
            @Html.TextBox("Password")
            @Html.ValidationMessageFor(model => model.Password)
        </div>
        <div class="editor-label">
            Confirm your password
        </div>
        <div class="editor-field">
            @Html.TextBox("ConfirmPassword");
            @Html.ValidationMessageFor(model => model.ConfirmPassword)
        </div>
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}
<div>
    @Html.ActionLink("Back to List", "Index")
</div>

我的代码失败了,因为我的模型当然不包含ConfirmPassword字段。 现在,有只小鸟告诉我AutoMapper可以解决这个问题。但是我无法弄清楚...请问有人能告诉我该怎么做才能让这个工作起来吗?我的AccountController现在看起来像这样:

private readonly AccountViewModel _viewModel = new AccountViewModel();
private readonly DatabaseEntities _database = new DatabaseEntities();

//
        // GET: /Account/Create

        public ActionResult Create()
        {
            Mapper.CreateMap<AccountViewModel, Account>();
            return View("Create", _viewModel);
        } 

        //
        // POST: /Account/Create

        [HttpPost]
        public ActionResult Create(AccountViewModel accountToCreate)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var newAccount = new Account();
                    Mapper.Map(accountToCreate, newAccount);
                   _database.Account.AddObject(newAccount);
        _database.SaveChanges();
                }

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

但是这并不起作用...(从http://weblogs.asp.net/shijuvarghese/archive/2010/02/01/view-model-pattern-and-automapper-in-asp-net-mvc-applications.aspx中得到的示例)

请问有人能在这个问题上给我启示吗?非常感谢,对于这个主题的大量问题和数百个问题,我表示歉意...

2个回答

18

关于您的代码,以下是一些注意事项:

  1. 您的视图使用强类型@model声明)绑定到了 Account 模型,而实际上应该绑定到 AccountViewModel 视图模型(如果不在视图中使用它,声明视图模型就没有意义)。
  2. AutoMapper 不用于验证,仅用于类型转换。
  3. 您不需要在控制器中声明一个 readonly 字段来存储视图模型(AccountViewModel)。您可以在 GET 操作内部实例化视图模型,并将其留给默认模型绑定器作为 POST 操作的参数进行实例化。
  4. 应该在整个应用程序中只执行一次 AutoMapper 配置(Mapper.CreateMap<TSource, TDest>),最好在 Application_Start 中完成,而不是在控制器操作内部完成。
  5. 您的视图模型中没有 Email 字段,这可能是更新失败的原因(尤其是如果这个字段在数据库中是必需的)。

下面是您的代码示例:

public ActionResult Create()
{
    var model = new AccountViewModel();
    return View("Create", model);
} 

[HttpPost]
public ActionResult Create(AccountViewModel accountToCreate)
{
    try
    {
        if (ModelState.IsValid)
        {
            var newAccount = Mapper.Map<AccountViewModel, Account>(accountToCreate);
           _database.Account.AddObject(newAccount);
           _database.SaveChanges();
        }
        return RedirectToAction("Index");
    }
    catch
    {
        return View();
    }
}

Darin,你再次救了我。这正是我长期以来一直寻找的东西。非常感谢你! - Matthias

3

将您的视图的第一行替换为

@model AutoMapperTest.AccountViewModel

同时,您只需要在应用程序生命周期内调用一次Mapper.CreateMap(例如,在应用程序启动时)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接