Samg
Samg

Reputation: 638

Mvc 3 validation of property that throws an exception

I have a property on my Model Class that performs a type conversion as follows:

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
          }  
       }
    }
}

Controller:

[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?

Upvotes: 2

Views: 1052

Answers (1)

Jesse
Jesse

Reputation: 8393

Rather than putting the try catch within your model, you could move the error handling to your controller code. For example if the tryupdatemodel throws an exception you could add a custom model error:

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);
}

Upvotes: 1

Related Questions