【问题标题】:Validate model on initial request根据初始请求验证模型
【发布时间】:2011-01-07 01:39:26
【问题描述】:

我在页面初始加载时将模型返回到我的视图,模型是从数据库中填充的,我想验证模型,以便当用户收到页面时,验证摘要会显示错误(如果有) .

我尝试过使用 TryValidateModel(model) 但这不起作用,它不会更新 ModelState,我认为它只会针对从 ModelBinder 填充的内容进行验证

这有什么问题吗?我只想先验证模型,而无需用户将其发回......

        [Authorize, HttpGet, ActionName("StepOne")]
    public ActionResult StepOneGET(StepOneModel model)
    {
        var individual = _onsideService.Get(User.Identity.Name);

        model.PersonalInformation = new PersonalInformationModel
                                        {
                                            FirstName = individual.FirstName,
                                            LastName = individual.LastName,
                                            DoB = individual.DateOfBirth.ToString("dd/MM/yyyy"),
                                            Email = individual.DefaultEmail.EmailAddress,
                                            Phone = individual.DefaultPhone.Number,
                                            AddressLine1 = location.Address1,
                                            AddressLine2 = location.Address2,
                                            City = location.City,
                                            PostCode = location.PostalCode,
                                            Country = location.Country
                                        };

        // NOTE: Does not update ModelState
        TryValidateModel(model);

        // Need to return potential errors to user on page load

        return View(model);     
    }

【问题讨论】:

  • 为什么您的 onsideService 的数据无效?
  • 你试过用if(!...) {...} 块包裹TryValidateModel() 吗?尝试调试,看看是否进入if块。
  • @Arnis 数据库可能有无效数据......现有系统有完美的有效数据......
  • @Krof TryValidateModel() 返回 true,即使模型无效,当我回发验证正常工作时,它仅与验证控制器中绑定的字段有关,因此我想要一种方法覆盖这个
  • "什么现有系统有完美的有效数据.." 每个系统在将数据保存到数据库之前都会正确验证数据。

标签: asp.net-mvc


【解决方案1】:

这是在another question 这里提供的一个 sn-p。我不认为它有任何功劳,但它应该完全符合你的要求。

public static IList<KeyValuePair<string, string>> GetErrors(object obj)
    {
        // get the name of the buddy class for obj
        MetadataTypeAttribute metadataAttrib = obj.GetType().GetCustomAttributes(typeof(MetadataTypeAttribute), true).FirstOrDefault() as MetadataTypeAttribute;

        // if metadataAttrib is null, then obj doesn't have a buddy class, and in such a case, we'll work with the model class
        Type buddyClassOrModelClass = metadataAttrib != null ? metadataAttrib.MetadataClassType : obj.GetType();

        var buddyClassProperties = TypeDescriptor.GetProperties(buddyClassOrModelClass).Cast<PropertyDescriptor>();
        var modelClassProperties = TypeDescriptor.GetProperties(obj.GetType()).Cast<PropertyDescriptor>();

        var errors = from buddyProp in buddyClassProperties
                           join modelProp in modelClassProperties on buddyProp.Name equals modelProp.Name // as this is an inner join, it will return only the properties that are in both the buddy and model classes
                           from attribute in buddyProp.Attributes.OfType<ValidationAttribute>() // get only the attributes of type ValidationAttribute
                           where !attribute.IsValid(modelProp.GetValue(obj))
                           select new KeyValuePair<string, string>(buddyProp.Name, attribute.FormatErrorMessage(string.Empty));

        return errors.ToList();
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-21
    • 2017-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-30
    相关资源
    最近更新 更多