开发者

Handling invalid values with ModelBinder in ASP.NET MVC 1.0

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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜