我在模拟类别上拥有财产,进行以下类型转换:
Model:
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);
}
What is the appropriate pattern to add an appropriate ModelError if the TimeSpan.Parse throws an exception? Currently it will give the generic error "The value "xxx" is invalid". How can I customize this to return a specific error?