Mvc 3验证抛出异常的属性

时间:2011-10-19 22:53:13

标签: asp.net-mvc asp.net-mvc-3 validation

我的Model Class上有一个属性,它按如下方式执行类型转换:

型号:

public class TimeClass
{
    private int timeInSeconds;

    [Required]
    public int Id {get;set;}

    [Required]
    public string Timer
    {
       get {
            TimeSpan ts = new TimeSpan(0,0,(int)timeInSeconds);
            return ts.ToString(@"mm\:ss",CultureInfo.InvariantCulture);
       }
       set {
          try {
             var ts = TimeSpan.ParseExact(value, @"mm\:ss", CultureInfo.InvariantCulture);
             timeInSeconds= Convert.ToInt32(ts.TotalSeconds);
          }
          catch {
             //Is it possible to add a validation error to the modelstate here
          }  
       }
    }
}

控制器:

[HttpPost]
public ActionResult Create(FormCollection collection)
{
  string[] whitelist = new[] {"Id", "Timer" };

  if (TryUpdateModel(quiz, whitelist))
  {
    //Save to Repo
    return RedirectToAction("Edit", new { Id = Id });
  }
  return View(tc);
}

如果TimeSpan.Parse引发异常,添加适当ModelError的适当模式是什么? 目前它将给出一般错误“值”xxx“无效”。如何自定义此选项以返回特定错误?

1 个答案:

答案 0 :(得分:1)

您可以将错误处理移动到控制器代码中,而不是将try catch放在模型中。例如,如果tryupdatemodel抛出异常,则可以添加自定义模型错误:

TimeClass model = new TimeClass();
string[] whitelist = new[] {"Id", "Timer" };
try
{
    UpdateModel(model);

    //Save to Repo
    return RedirectToAction("Edit", new { Id = Id });
}
catch
{
    // Generate error
    ModelState.AddModelError(string.Empty, "Model Error Here");

    return View(tc);
}