Validating a nested model model in an ASP.Net MVC model

I have an application with a company model. The company model has the navigation property for the address model (one-to-one relationship):

Company.cs

public class Company
{
    public int CompanyID { get; set; }
    public string Name { get; set; }

    // Snip...

    public virtual Address Address { get; set; }
}

I created a view model for editing, detailing and creating actions:

CompanyViewModel.cs

public class CompanyViewModel
{
    public int CompanyID { get; set; }

    [Required]
    [StringLength(75, ErrorMessage = "Company Name cannot exceed 75 characters")]
    public string Name { get; set; }

    // Snip...

    public Address Address { get; set; }
}

I use AutoMapper in my controller to map between model and view model, and everything works correctly. However, now I want to use verification on the address object - I do not want the company to be created without the presence of the address.

My first thought was a simple route - I tried putting the [Required] annotation in the Address property. It did nothing.

, Address , Address:

public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string PostalCode { get; set; }
// etc....

, AutoMapper Company "", :

public ActionResult Details(int id = 0)
{
    // Snip code retrieving company from DB

    CompanyViewModel viewModel = new CompanyViewModel();
    viewModel.Name = company.Name;
    viewModel.Address1 = company.Address.Address1;

    // Snip...    

    return View(viewModel);
}

AutoMapper... ( )?

Address , ?

AutoMapper , ?

+4
1

, automapper , " ": , .

, ViewModel

public int CompanyID { get; set; }

    [Required]
    [StringLength(75, ErrorMessage = "Company Name cannot exceed 75 characters")]
    public string Name { get; set; }

    // Snip...
    //Address is the navigation property in Company, Address1 is the desired property from Address
    public string AddressAddress1 { get; set; }
    public string AddressAddress2 { get; set; }
    public string AddressCity { get; set; }
    public string AddressPostalCode { get; set; }
}

, AutoMapper , :

Mapper.CreateMap<Company, CompanyViewModel>()
.ForMember(dest => dest.Address1, opt => opt.MapFrom(src => src.Address.Address1));
+2

All Articles