ASP.NET MVC by default: ints too long, empty validation error message

I have the following model class (filmed for simplicity):

public class Info { public int IntData { get; set; } } 

Here is my Razor form using this model:

 @model Info @Html.ValidationSummary() @using (Html.BeginForm()) { @Html.TextBoxFor(x => x.IntData) <input type="submit" /> } 

Now, if I enter non-numeric data in a text field, I get the correct check message, that is: "The value" qqqqq "is not valid for the field" IntData ".

But if I enter a very long sequence of numbers (e.g. 345234775637544), I get a validation summary.

In my controller code, I see that ModelState.IsValid is false , as expected, and ModelState["IntData"].Errors[0] looks like this:

 {System.Web.Mvc.ModelError} ErrorMessage: "" Exception: {"The parameter conversion from type 'System.String' to type 'System.Int32' failed. See the inner exception for more information."} (exception itself) [System.InvalidOperationException]: {"The parameter conversion from type 'System.String' to type 'System.Int32' failed. See the inner exception for more information."} InnerException: {"345234775637544 is not a valid value for Int32."} 

As you can see, the check works fine, but does not give the user an error message.

Can I customize the default model binding behavior so that the correct error message is displayed in this case? Or do I need to write my own binder?

+7
source share
2 answers

One way would be to write a custom mediator:

 public class IntModelBinder : DefaultModelBinder { public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); if (value != null) { int temp; if (!int.TryParse(value.AttemptedValue, out temp)) { bindingContext.ModelState.AddModelError(bindingContext.ModelName, string.Format("The value '{0}' is not valid for {1}.", value.AttemptedValue, bindingContext.ModelName)); bindingContext.ModelState.SetModelValue(bindingContext.ModelName, value); } return temp; } return base.BindModel(controllerContext, bindingContext); } } 

which can be registered in Application_Start :

 ModelBinders.Binders.Add(typeof(int), new IntModelBinder()); 
+8
source

How to set MaxLength in input field up to 10 or so? I would do this in conjunction with setting the range for IntData. Unless, of course, you want the user to enter 345234775637544. In that case, you're better off with a string.

+1
source

All Articles