gpt4 book ai didi

validation - Controller.ValidateModel 方法。它是如何工作的?

转载 作者:行者123 更新时间:2023-12-04 04:30:35 25 4
gpt4 key购买 nike

我有以下模型类:

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(model) 的行为对我来说很奇怪,它是一个“黑匣子”......

最佳答案

ValidateModel()如果模型无效,则抛出异常。相反,使用 TryValidateModel()
来自 documentation

The TryValidateModel() is like the ValidateModel() method except that the TryValidateModel() method does not throw an InvalidOperationExceptionexception if the model validation fails.

关于validation - Controller.ValidateModel 方法。它是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30259820/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com