views:

113

answers:

2

Hey all.

First of all some context:

I have a form, where I post back some objects that are automatically materialized into objects by MVCs built-in ModelBinder:

<input type="hidden" name="myobj[0].Id" />
<input type="text" name="myobj[0].Hours" />
<input type="hidden" name="myobj[1].Id" />
<input type="text" name="myobj[1].Hours" />

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Save(IList<MyObject> myobj);

Additionally: I would like to stress that we are posting to DTO (DataTransferObjects) that we further down the line map into entity framework entities, so we would rather not like the change anything on the DTO's except maybe adding attributes.

Problem

If a user enters an invalid value for "Hours", say 'Fubar', then the ModelBinder naturally will not attempt to set the 'Hours'-property. But it defaults to 0, because it is an int and not a string.

This causes some difficulty for me ofcourse, because now I can't see if the user actually entered 0, or if this was caused by invalid input.

Since I am using a home-rolled object-to-entity (Entity Framework) mapper, we cannot change the foot-print of the 'Hours'-property to int?. I am aware that MVC has some built in Validation, but we would rather not implement that since we know it has been wildly attacked and that there is some new validation coming in ASP.NET MVC 2.0.

Solution?

I need to be able to point out to the user which field is incorrect, so that means I somehow need to be able to catch an exception (or possibly some other ingenious solution?), where I can do some logic and post back a new view to the user where I clarify what they did incorrectly.

My current idea: Writing a custom ModelBinder.

What do you suggest?

A: 

This causes some difficulty for me ofcourse, because now I can't see if the user actually entered 0, or if this was caused by invalid input.

Yes you can. Look in the ModelState.

Craig Stuntz
A: 

While this is not particularly ideal, you've stated that you don't want to change anything else. So the option you mentioned, creating a custom ModelBinder will work fine. However, you might find yourself creating a ModelBinder for each entity that you want to bind.

statichippo
yeah, I'm not going to be doing that ;) .. but thanks for the input
CodeMonkey