Validating a view model containing nested domain objects

I have the following two objects:

 public class Product
{
    [Key]
    public int ID { get; set; }
    [Required]
    public string Name { get; set; }
    public virtual Category Category { get; set; }
}
public class Category
{
    [Key]
    public int ID { get; set; }
    [Required]
    public string Name { get; set; }
    public ICollection<Product> Products { get; set; }
}

and presentation model

public class ProductCreateOrEditViewModel
{
    public Product Product { get; set; }
    public IEnumerable<Category> Categories { get; set; }
}

The create for Product view uses this ViewModel. The category identifier is defined as follows in the view:

<div class="editor-field">
@Html.DropDownListFor(model => model.Product.Category.ID,new SelectList   
(Model.Categories,"ID","Name"))
    @Html.ValidationMessageFor(model => model.Product.Category.ID)
</div>

When I receive an instance of the view model in the form messages with the product and the selected object category object, but since the category โ€œNameโ€ property has the [Required] attribute, ModelState is invalid.

Regarding the creation of the product, I do not need or do not need the Name property. How can I get model binding to work so it doesn't report as a ModelState error?

+3
source share
1 answer

You must create the correct ViewModel for your view.

imo , .

DTO .

,

public class ProductViewModel
{
   public int ID { get; set; }
   [Required]
   public string Name { get; set; }
   public int CategoryId? { get; set; }
   public SelectList Categories { get; set; }
}

public ViewResult MyAction(int id)
{
   Product model = repository.Get(id);

   //check if not null etc. etc.

   var viewModel = new ProductViewModel();
   viewModel.Name = model.Name;
   viewModel.CategoryId = model.Category.Id;
   viewModel.Categories = new SelectList(categoriesRepo.GetAll(), "Id", "Name", viewModel.CategoryId)

   return View(viewModel);
}

, , viewModel

[HttpPost]
public ViewResult MyAction(ProductViewModel viewModel)
{
   //do the inverse mapping and save the product
}

,

+3

All Articles