Is there any way to ignore some properties (on a POCO) when validating a form in ASP.NET MVC3?

前端 未结 9 600
春和景丽
春和景丽 2021-02-05 05:59

i\'ve got a sign up wizard for new user registration. When I try to goto the 2nd page, I get validation errors because my User object hasn\'t been fully populated,

9条回答
  •  时光说笑
    2021-02-05 06:57

    I was just messing with validation forms and ModelState and found out a very easy solution to your problem without writing any new method, overrides etc.

    ModelState.Where(m => m.Key == "Avatar").FirstOrDefault().Value.Errors.Clear();
    // At  this point ModeState will have an error for that Key,
    // by applying Clear it remove the error so modelstate becomes valid again
    
    if (!ModelState.IsValid) {
        return View("User", model);
    } else {     
        try  {
            // do something
        } catch {
            TempData["errorMessage"] = "something went wrong";
        }
    }
    

提交回复
热议问题