views:

29

answers:

1
  1. consider classic example: Product and Category
  2. editing Product
  3. in dropdown Id of Category is selected - Category mapped as object with all fields empty except Id
  4. when submitting Product edit form - validation gives an error: "Category name is required" (I have Required attribute on Category Name property)

How deal with such errors if I want to use built-in validation (if (!ModelState.IsValid))? Writing custom data binder which would fill all such id-only-objects with values from database comes to mind.

Do you have any other solutions for this problem?

+1  A: 

Hi,

You need to pass back your edited product and the category id. Then in you controller/repository get the category from the passed category id and set the category as the product category.

As the category is returned from the db (or wherever) all the properties should be propulates so you shouldn't get "Category name is required"

A quick example of what I mean:

[HTTPost]
public ActionResult Save(Product product, int? categoryId)
{
  Category category = GetCategory(categoryID);

  product.Category = category;

  if (ModelState.IsValid)
  {
    // Save etc.
  }
}
Simon G
not really what I wanted: I still have manually bind objects in every controller action. I thought about generic binder which would work with all objects. But still it is a acceptable solution
kilonet
just checked your code: unfortunately it doesn't work: ModelState still is !IsValid after loading Category
kilonet
Are you using entity framework, nhibernate or something else. If you want something generic for model binding you should have a look at http://automapper.codeplex.com/ - this maps your ui to objects. What happens when you try debugging you app before you check the modelstate, is the category populated?
Simon G
Category populated just fine, but it seems that Product parameter of action method has no influence on ModelState.IsValid
kilonet