Okay, I have done a different approach. I am not sure if this is any more elegant. Upon my research I came across AutoMapper and have done this. If anyone has a better solution to my problem, please let me know. :-)
public static class AutoMapperWebConfiguration
{
public static void Configure()
{
Mapper.Initialize(cfg =>
{
cfg.AddProfile(new CustomerMapper());
cfg.AddProfile(new CustomerAddressMapper());
});
}
}
public class CustomerMapper : Profile
{
protected override void Configure()
{
Mapper.CreateMap<CustomerViewModel, Customer>().ForMember(customer => customer.Address, expression => expression.MapFrom(viewModel => viewModel.Address));
}
}
public class CustomerAddressMapper : Profile
{
protected override void Configure()
{
Mapper.CreateMap<CustomerAddressViewModel, Address>();
}
}
Global.asax:
AutoMapperWebConfiguration.Configure();
My ViewModels
is then
public class CreateAccountViewModel
{
public CustomerViewModel Customer { get; set; }
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
public string ConfirmPassword { get; set; }
}
public class CustomerViewModel
{
[Required]
[Display(Name = "Company Name")]
public String CompanyName { get; set; }
[Required]
[Display(Name = "CVR")]
public String CVR { get; set; }
[Required]
[Display(Name = "First name")]
public String FirstName { get; set; }
[Required]
[Display(Name = "Last name")]
public String LastName { get; set; }
[Required]
[Display(Name = "Phone (mobile)")]
public String Phone { get; set; }
[Required]
[Display(Name = "E-mail")]
public String Email { get; set; }
public CustomerAddressViewModel Address { get; set; }
}
public class CustomerAddressViewModel
{
[Required]
[Display(Name = "Streey")]
public String Street { get; set; }
[Required]
[Display(Name = "Postal code")]
public String PostalCode { get; set; }
[Required]
[Display(Name = "City")]
public String City { get; set; }
[Required]
[Display(Name = "Country")]
public String Country { get; set; }
}
And finally my action
, which takes the CreateAccountViewModel
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(CreateAccountViewModel model)
{
if (ModelState.IsValid) {
Customer customer = Mapper.Map<Customer>(model.Customer);
var user = new ApplicationUser() { UserName = model.UserName, Customer = customer };
var result = UserManager.Create(user, model.Password);
if (result.Succeeded)
{
await SignInAsync(user, false);
return RedirectToAction("Index", "Home");
}
else
{
AddErrors(result);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}