Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to use AutoMapper in ASP.Net MVC

I'm trying to start using ViewModels - but I'm having trouble with this POST not validating - the values in the model are shown in the Watch part below the code:

ModelStats.IsValid = false

Invalid ModelState

My ItemViewModel is:

  public class ItemViewModel
  {
    public int ItemId { get; set; }
    [Display(Name = "Item")]
    public string ItemName { get; set; }
    [Display(Name = "Description")]
    public string Description { get; set; }
    [Display(Name = "Price")]
    public double UnitPrice { get; set; }
    [Range(0.00, 100, ErrorMessage = "VAT must be a % between 0 and 100")]
    public decimal VAT { get; set; }
    [Required]
    public string UserName { get; set; }
   }

I'm sure it will be something simple - but I've just been looking at it so long, I can't figure out what I'm doing wrong. Can anyone please advise?

Thanks, Mark

like image 518
Mark Avatar asked May 10 '13 07:05

Mark


2 Answers

As far as Validation failure is concerned.

If you don't intend to supply UserName in the form, then remove the [Required] attribute from ItemViewModel


In order to Use AutoMapper. You need to create a map, such as

 Mapper.CreateMap<Item, ItemViewModel>();

And then map

var itemModel = Mapper.Map<Item, ItemViewModel>(model);

Note: CreateMap has to be created only once, you should register it at Startup. Do read How do I use AutoMapper?.

like image 111
Satpal Avatar answered Sep 22 '22 03:09

Satpal


Make sure your ItemViewModel, Item classes have same fields or not. If same fields with same Datatypes AutoMapper works fine.

Mapper.CreateMap< Item, ItemViewModel>();

Mapper.Map< Item, ItemViewModel>(ItemVM);

If Fields are not same in both the classes make sure that same with Custom Mapping.

Mapper.CreateMap<UserDM, UserVM>().ForMember(emp => emp.Fullname,
map => map.MapFrom(p => p.FirstName + " " + p.LastName));

In the above Custom Mapping Fullname is UserVM field that maps with FirstName, LastName fields from UserDM (here UserDM is Domain Model, UserVM is View Model).

like image 43
Adi Avatar answered Sep 24 '22 03:09

Adi