0
  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?

2
  • You shouldn't be posting any Categories back with a Product edit form, only the category Id on the product. Can we see some code. Commented Aug 27, 2010 at 10:14
  • I agree with you. But asp.net mvc binding mechanism, when validating binded Product object, whants all required fields of Product.Category to be present. I believe i need to fill Category properties somewhere between binding and validation Commented Aug 27, 2010 at 10:20

1 Answer 1

1

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.
  }
}
Sign up to request clarification or add additional context in comments.

4 Comments

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
just checked your code: unfortunately it doesn't work: ModelState still is !IsValid after loading Category
Are you using entity framework, nhibernate or something else. If you want something generic for model binding you should have a look at 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?
Category populated just fine, but it seems that Product parameter of action method has no influence on ModelState.IsValid

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.