FormCollection System.Web.Mvc.ModelErrorCollection
csharp newpie here, i have the following controller action that processes a strongly typed view form, some values im processing manually from fromCollection, it they are em开发者_Go百科pty then i get this error:
{ Key = carCount , Errors = System.Web.Mvc.ModelErrorCollection }
but if there are incoming values e.g. "0", "1" etc then its fine!
[HttpPost]
public ActionResult create(Trip trip, FormCollection collection)//Trip trip
{
trip.carCount = TryToParse(collection["carCount"]);//int
trip.busCount = TryToParse(collection["busCount"]);//int
trip.truckCoun = TryToParse(collection["truckCount"]);//int
var errors = ModelState
.Where(x => x.Value.Errors.Count > 0)
.Select(x => new { x.Key, x.Value.Errors })
.ToArray();
foreach (var error in errors)
{
System.Diagnostics.Debug.WriteLine(error);
}
more code................
This is the method to convert string to int, which works perfectly fine:
private int TryToParse(string value)
{
if (value.Trim() == "" || value.Trim() == null) value = "0";
int number;
bool result = int.TryParse(value, out number);
return number;
}
Any thoughts? thanks
The default model binder which runs before your action sees that you have this Trip
model as parameter to your action and tries to set its properties from the request. Now because you have defined those 3 properties as integers if the Request contains empty values for them, during the binding the default model binder will of course not be able to convert an empty strong to an integer and automatically add an error to the ModelState. Then the controller actin is invoked and all you do is to reset the values of this trip object but of course the error that was added to ModelState is left and that's what you observe.
So the solution to this problem would be to write a custom model binder or make those properties nullable integers:
public int? CarCount { get; set; }
public int? BusCount { get; set; }
public int? TruckCount { get; set; }
and then have your action look like this:
public ActionResult Create(Trip trip)
{
if (!ModelState.IsValid)
{
// there were errors => redisplay the view
return View(trip);
}
// at this stage the model is valid => process it
...
}
精彩评论