Asp.net mvc 3 FormCollection System.Web.Mvc.ModelErrorCollection
csharp newpie在这里,我有以下处理强类型视图表单的控制器操作,我从fromCollection手动处理一些值,如果这些值为空,那么我会得到此错误:Asp.net mvc 3 FormCollection System.Web.Mvc.ModelErrorCollection,asp.net-mvc-3,Asp.net Mvc 3,csharp newpie在这里,我有以下处理强类型视图表单的控制器操作,我从fromCollection手动处理一些值,如果这些值为空,那么我会得到此错误: { Key = carCount , Errors = System.Web.Mvc.ModelErrorCollection } 但如果有输入值,例如“0”、“1”等,则可以 [HttpPost] public ActionResult create(Trip trip, FormCollection collecti
{ Key = carCount , Errors = System.Web.Mvc.ModelErrorCollection }
但如果有输入值,例如“0”、“1”等,则可以
[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................
这是一种将字符串转换为int的方法,它工作得非常好:
private int TryToParse(string value)
{
if (value.Trim() == "" || value.Trim() == null) value = "0";
int number;
bool result = int.TryParse(value, out number);
return number;
}
有什么想法吗?
谢谢在您的操作之前运行的默认模型绑定器会看到您将此
Trip
模型作为操作的参数,并尝试根据请求设置其属性。现在,由于您已经将这3个属性定义为整数(如果请求包含它们的空值),因此在绑定期间,默认模型绑定器当然无法将空的strong转换为整数,并自动向ModelState添加错误。然后调用控制器actin,您所要做的就是重置这个trip对象的值,当然,添加到ModelState的错误被保留,这就是您观察到的
因此,这个问题的解决方案是编写一个自定义模型绑定器或使这些属性成为可为空的整数:
public int? CarCount { get; set; }
public int? BusCount { get; set; }
public int? TruckCount { get; set; }
然后让你的动作看起来像这样:
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
...
}