In a project using NHibernate, I have this class :
public class AdminVAT : IAdminDecimal
{
public virtual int Id { get; set; }
public virtual int Code { get; set; }
public virtual decimal Value { get; set; }
}
In ASP.NET MVC, I’d like some validation or/and some formatting on some fields. Then I tried this, using AutoMapper :
public class AdminVATDTO : AdminVAT
{
[DisplayFormat(DataFormatString = "{0:n2}", ApplyFormatInEditMode = true)]
public override decimal Value { get; set; }
}
In the Controller :
IList<AdminVAT> listAdminVAT = new AdministrationService(session).ListDecimal<AdminVAT>();
AutoMapper.Mapper.CreateMap<AdminVAT, AdminVATDTO>();
model.ListVAT = AutoMapper.Mapper.Map<IList<AdminVAT>, IList<AdminVATDTO>>(listAdminVAT);
In the HTML :
@Html.DropDownList("ddVAT", new SelectList(Model.ListVAT, "Id", "Value", Model.Estimation.AdminVAT))
The “Value” field is a decimal, when I display it on the page, I have 5 decimal, I need 2. The request here is simple but may be more complexe later on other field in other classes. In this case, that’s not work, but work on other classes using the same way.
In a previous past someone (Darin) told me it was not a good way to use AutoMapper to do this … the question is. Wich is thge best way to do this ?
Edit : and no code in the cshtml file
Thanks,
I am afraid that there are some serious issues with your models. It seems as if this
AdminVATDTOis intended as a view model provided the fact that it has some formatting attributes on it but view models should never derive from models. That’s not correct design.Here’s a correct design:
Domain model (not changing this as I suppose this already exists):
View models:
then define a mapping between
AdminVATandAdminVATViewModel:and then in your controller action:
and finally in the view: