我有以下模型类:
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;
}
}
使用“经典”可以正常使用:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Plugandabandon.ViewModels.AddCompanyViewModel model)
{
if (ModelState.IsValid)
{
CreateCompany(model);
return RedirectToAction("Index");
}
else
{
return View(model);
}
}
但是我想将这个模型类用于另一个,ajax形式。 我有以下方法:
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);
}
看看
ValidateModel(model);
线。如果模型是正确的 - 它工作正常。如果不正确 - 它会抛出异常并中断方法的继续执行(并返回异常以查看)。另外,如果我在
上设置断点public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
方法,它永远不会在无效的模型案例中调用! (调用有效模型Validate方法)。我想拥有像“经典”方法这样的行为,只需验证模型然后验证ModelState.IsValid。 ValidateModel(模型)的行为对我来说很奇怪,它是一个“黑盒子”......
答案 0 :(得分:3)
ValidateModel()
会抛出异常。相反,请使用TryValidateModel()
TryValidateModel()与ValidateModel()方法类似,只是如果模型验证失败,TryValidateModel()方法不会抛出InvalidOperationException异常。