Note that there are some explanatory texts on larger screens.

plurals
  1. POValidation of nested models in view model in ASP.Net MVC
    primarykey
    data
    text
    <p>I have an application with a Company model. The Company model has a navigation property to an Address model (one-to-one relationship):</p> <p><strong>Company.cs</strong></p> <pre><code>public class Company { public int CompanyID { get; set; } public string Name { get; set; } // Snip... public virtual Address Address { get; set; } } </code></pre> <p>I've created a view model to handle the edit, detail, and create actions:</p> <p><strong>CompanyViewModel.cs</strong></p> <pre><code>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; } } </code></pre> <p>I'm using AutoMapper in my controller to map back and forth between the model and view model, and everything is working properly. However, I now want to use validation on the address object - I do not want a company to be created without an address being present.</p> <p>My first thought was the simple route - I tried putting a '[Required]' annotation on the Address property. This didn't do anything.</p> <p>I then thought it would be better to do away with the Address property and abstract that data in the view model, so I added properties to the view model for all the properties in my Address class:</p> <pre><code>public string Address1 { get; set; } public string Address2 { get; set; } public string City { get; set; } public string PostalCode { get; set; } // etc.... </code></pre> <p>This seemed like good practice, but now my AutoMapper can't map these properties to the Company class' Address object, so I had to manually map in the controller:</p> <pre><code>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); } </code></pre> <p>This leads to a lot of extra code in my controller instead of a nice one-line AutoMapper statement...so what's the right way to deal with this (validation of nested models in a view model)?</p> <p>Is it good practice to expose the Address property directly in the view model, or better to abstract it out with separate properties like I have done?</p> <p>Can AutoMapper work in a situation where source and destination are not exact matches?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload