Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 4612956
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 22, 20262026-05-22T01:28:37+00:00 2026-05-22T01:28:37+00:00

(Again, an MVC validation question. I know, I know…) I’d like to use AutoMapper

  • 0

(Again, an MVC validation question. I know, I know…)

I’d like to use AutoMapper (http://automapper.codeplex.com/) to validate fields in my Create Views for fields that are not in my database (and thus not in my DataModel).

Example: I have an Account/Create View for users to create a new account and I want both a Password and ConfirmPassword field so users have to enter their password twice for confirmation.

The Account table in the database looks like this:

Account[Id(PK), Name, Password, Email]

I’ve generated an ADO.NET Entity Data Model and from that, I generated the Models using an ADO.NET Self-Tracking Entity Generator.

I’ve also written a custom AccountViewModel for validation annotations like [Required].

So, to summarize, this is my project structure:

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

The code of my AccountViewModel looks like this:

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; }
    }

Now, my Create View looks like this:

@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>

My code fails because my Model does not contain the ConfirmPassword field of course.
Now, a little bird whispered to me the AutoMapper could fix that for me. But I can’t figure it out… Can someone please tell me what I have to do to make this work? My AccountController looks like this now:

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();
            }
        }

But this doesn’t work… (Got the example from http://weblogs.asp.net/shijuvarghese/archive/2010/02/01/view-model-pattern-and-automapper-in-asp-net-mvc-applications.aspx)

Can anyone please enlighten me on this matter? Thank you very much, and my apologies for the wall of text and the hundreds of questions about the same subject…

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-22T01:28:38+00:00Added an answer on May 22, 2026 at 1:28 am

    Few remarks about your code:

    1. Your view is strongly typed (@model declaration) to the Account model whereas it should be typed to the AccountViewModel view model (there is no point in declaring a view model if you don’t use it in the view).
    2. AutoMapper is not used for validation, only for converting between types
    3. You don’t need to declare a readonly field for your view model (AccountViewModel) inside the controller. You could instantiate the view model inside the GET action and leave the default model binder instantiate it as action argument for the POST action.
    4. You should do the AutoMapper configuration (Mapper.CreateMap<TSource, TDest>) only once for the entire application (ideally in Application_Start) and not inside a controller action
    5. There is no Email field on your view model which might be the reason for the update to fail (especially if this field is required in your database)

    So here’s how your code might look like:

    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();
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Once again a very beginner-ish question, but here I go: I would like to
In a recent question posed here: ASP.NET MVC: Is Data Annotation Validation Enough? ...it
Hello again ladies and gents! OK, following on from my other question on ASP.NET
Yet again, my teacher was unable to answer my question. I knew who may
I have been looking at many ASP.Net MVC client side validation ideas including xVal.
With client-side validation turned on in ASP.NET MVC 2 RC2, the validation summary message
I need to set the ErrorMessage property of the DataAnnotation's validation attribute in MVC
I use a foreach loop inside ASP.NET MVC View page. For each element of
I'm building an ASP.NET MVC site where I plan to use Lucene.Net. I've envisioned
Once again one of those: Is there an easier built-in way of doing things

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.