Controller.ValidateModel. How it works?

I have the following model class:

public abstract class CompanyFormViewModelBase
{
    public CompanyFormViewModelBase()
    {
        Role = new CompanyRoleListViewModel();
        ContactPerson = new PersonListViewModel();
        Sector = new SectorListViewModel();
    }
    [Required]
    [Display(Name = "Company Name")]
    public string CompanyName { get; set; }
    public CompanyRoleListViewModel Role { get; set; }
    [Display(Name = "Contact Name")]
    public PersonListViewModel ContactPerson { get; set; }
    public SectorListViewModel Sector { get; set; }
}
public class AddCompanyViewModel : CompanyFormViewModelBase, IValidatableObject
{
    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        PlugandabandonEntities db = new PlugandabandonEntities();
        CompanyName = CompanyName.Trim();

        var results = new List<ValidationResult>();

        if (db.Company.Where(p => p.CompanyName.ToLower() == CompanyName.ToLower()).Count() > 0)
            results.Add(new ValidationResult("Company already exists.", new string[] { "CompanyName" }));
        return results;
    }
}

      

It works great with "classic" using:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(Plugandabandon.ViewModels.AddCompanyViewModel model)
    {
        if (ModelState.IsValid)
        {
            CreateCompany(model);
            return RedirectToAction("Index");
        }
        else
        {
            return View(model);
        }
    }

      

But I want to use this model class for another ajax form. I have the following method:

   public JsonResult ReturnJsonAddingCompany(string companyName, int roleID, int sectorID, int personID)
    {
        Plugandabandon.ViewModels.AddCompanyViewModel model = new ViewModels.AddCompanyViewModel()
        {
            CompanyName = companyName,
            ContactPerson = new ViewModels.PersonListViewModel()
            {
                SelectedItem = personID
            },
            Role = new ViewModels.CompanyRoleListViewModel()
            {
                SelectedItem = roleID
            },
            Sector = new ViewModels.SectorListViewModel()
            {
                SelectedItem = sectorID
            }
        };

        ValidateModel(model);

        if (ModelState.IsValid)
        {
            CreateCompany(model);
        }
        else
        {
            throw new Exception("Company with such name already exists");
        }

        var list = Utils.CompanyList();
        return Json(list, JsonRequestBehavior.AllowGet);
    }

      

Take a look

    ValidateModel(model);

      

lines. If the model is correct, it works fine. If not correct, it throws an exception and interrupts the continuation of the method (and returns an exception for viewing). Also, if I set a breakpoint to

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)

      

it was never called in an invalid model case! (with a valid model the Validate method is called). I want the behavior to be similar to the "classic" method, just check the model and then check ModelState.IsValid. The behavior of ValidateModel (model) is very strange for me, it is a "black box" ...

+3


source to share


1 answer


ValidateModel()

throws an exception if the model is invalid. Use insteadTryValidateModel()

From the documentation



TryValidateModel () is similar to ValidateModel (), except that TryValidateModel () does not throw an InvalidOperationException if model validation fails.

+3


source







All Articles