MVC - 验证域模型

时间:2017-12-21 17:04:39

标签: c# asp.net-mvc validation

我有一个ASP.NET MVC应用程序,并希望在两个级别上进行验证 - 视图模型验证和基于数据注释属性的域模型验证。视图模型验证工作简单:

public class CustomerFormVM
{
    [Required]
    [Display(Name = "Name")]
    public string Name { get; set; }
    [Required]
    [Display(Name = "Street")]
    public string Street { get; set; }
    [Required]
    [Display(Name = "City")]
    public string City { get; set; }
    [Required]
    [Display(Name = "State")]
    public string State { get; set; }
}

然后在控制器中调用:

        if (ModelState.IsValid)
        {

我有相同的域模型类:

public class CustomerFormPoco
{
    [Required]
    [Display(Name = "Name")]
    public string Name { get; set; }
    [Required]
    [Display(Name = "Street")]
    public string Street { get; set; }
    [Required]
    [Display(Name = "City")]
    public string City { get; set; }
    [Required]
    [Display(Name = "State")]
    public string State { get; set; }
}

但如何验证?

// viewmodel is CustomerFormVM object
var pocoModel = mapper.Map<CustomerFormPoco>(viewmodel);

如果我不检查“视图模式”。变量然后我得到了pocoModel&#39;可变的可变名称,街道,城市......

如何调用验证并做出决定取决于结果?

1 个答案:

答案 0 :(得分:0)

这样的事情怎么样?

if (!string.IsNullOrEmpty(pocoModel.Name) && !string.IsNullOrEmpty(pocoModel.Street) && !string.IsNullOrEmpty(pocoModel.City) && !string.IsNullOrEmpty(pocoModel.State))
{
    // Code here
}

我可能会用这样的冗余来做这件事:

string[] fields = new string[] { pocoModel.Name, pocoModel.Street, pocoModel.City, pocoModel.State };
bool isValid = true;
foreach (string field in fields)
{
    if (string.IsNullOrEmpty(field))
    {
        isValid = false;
        break;
    }
}
if (isValid)
{
    // Code here
}