5

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

4

2 回答 2

13

就验证失败而言。

如果您不打算UserName在表单中提供,请[Required]ItemViewModel


为了使用AutoMapper。您需要创建一个地图,例如

 Mapper.CreateMap<Item, ItemViewModel>();

然后地图

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

注意:CreateMap必须只创建一次,您应该在启动时注册它。请阅读如何使用 AutoMapper?.

于 2013-05-10T07:58:16.123 回答
1

确保您的ItemViewModel,Item类是否具有相同的字段。如果具有相同数据类型的相同字段 AutoMapper 工作正常。

Mapper.CreateMap< Item, ItemViewModel>();

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

如果两个类中的字段不相同,请确保与自定义映射相同。

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

在上面的自定义映射中,FullnameUserVMFirstName,映射的LastName字段UserDM(这里UserDM是域模型,UserVM是视图模型)。

于 2016-06-07T12:19:25.853 回答