What is the difference between ModelError and ValidationResult?

拟墨画扇 提交于 2019-12-10 13:18:08

问题


In ASP.NET MVC there exists a ModelState class that contains ModelErrorCollection. And a ModelError represents an error the occurs during model binding.

I know that ValidationResult is returned from ValidationAttribute.IsValid Method, and validates the specified value with respect to the current validation attribute. I understand that we can inherit from validationAttribute and override IsValid() in order to write a custom model validation attribute.

Example of using ModelState: http://www.asp.net/mvc/tutorials/older-versions/models-(data)/performing-simple-validation-cs

Example of using ValidationResult: http://www.codeproject.com/Articles/260177/Custom-Validation-Attribute-in-ASP-NET-MVC

How do these two work together? Or not work together? What is the intersection? This question is trying to understand ASP.NET MVC validation approaches better.

Why am I interested and why not just use data annotations? The answer is, I want to better understand validation for dynamic fields in ASP.NET MVC. In my product context, I will not have a model of pre-determined properties to attach validationAttributes to.


回答1:


I am new to ASP.NET MVC. From my understanding of the 2 you mentioned.

ValidationResult give us the ability to custom our error message linked to a property method by simply implement the IValidatableObject and get each model to define the Validate method. So from my point of view, ValidationResult is more like a feature used for configure the conditions and results of model validation.

ModelState give us the possibility to make our custom error from ValidationResult as part of the ModelState by doing ModelState.AddModelError(memberName, validationResult.ErrorMessage)

And With the combination of ValidationResult and ModelState, we can still using if (ModelState.IsValid) in our controller while the internal behavior already contains our custom error message and validation conditions.

Patrick had posted an detailed article regarding the validation in MVC, you can refer to here



来源:https://stackoverflow.com/questions/22210694/what-is-the-difference-between-modelerror-and-validationresult

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!