Remove object from modelstate validation

asp.net asp.net-mvc entity-framework

Question

I have two models:

public class UserInfo
{
    public long ID { get; set; }

    [Required]
    [StringLength(50)]
    public string FirstName { get; set; }

    //...

    public bool Falg{ get; set; }
}

public class UserInfoExtra
{
    public long ID { get; set; }

    [Required]
    public string PhoneNumber { get; set; }

    //...
}

Those two models are combined in a ViewModel:

public class UserViewModel
{
    public UserInfo UserInfo { get; set; }
    public UserInfoExtra ExtraInfo { get; set; }
}

In the controller:

public ActionResult Create(UserViewModel userinfo)
{
    if(userInfo.Flag){
        //Remove ExtaInfo from validation in ModelState.IsValid?
    }
    if (ModelState.IsValid)
    {
        db.UserInfos.Add(userinfo);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(userinfo);
}

How can I remove the ExtraInfo from validation in ModelState.IsValid?

1
2
6/10/2014 12:45:35 AM

Accepted Answer

Removing errors from ModelState is not a good idea. If you don't want the UserInfoExtra class to be validated when using the UserViewModel, then you should define your View Model differently (like below), and then use conditional validation on the PhoneNumber property:

public class UserViewModel
{
    public UserInfo UserInfo { get; set; }
    public long ID { get; set; }
    //[RequiredIf] (conditional validation here)...
    public string PhoneNumber { get; set;}
}

Here you can find an implementation of RequiredIf attribute: RequiredIf Conditional Validation Attribute

3
5/23/2017 12:30:01 PM

Popular Answer

  1. Ignore other properties(other than UserInfo) : ModelState.IsValidField(UserInfo)
  2. Clear/Remove property error : ModelState["ExtraInfo"].Errors.Clear();
  3. Create custom validator, as also suggested by ataravati : MVC Custom validation attribute


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow