In Suteki.shop, the realization of its own data verification mechanism, it can be said that the design of the idea is still very valuable reference. With this mechanism it is also easy to add a checksum to the corresponding entity object (attribute) in model. Here's how to implement it.
First, take a look at this class diagram:
Define a "Ivalidatingbinder" interface in Suteki.shop that derives from Imodelbinder:
An overloaded method updatefrom is defined in its interface, and the functionality to be implemented is the same as Updatefrom in MVC, which automatically reads some of the elements that we define in form and what they contain.
The class that implements the Ivalidatingbinder interface is called: Validatingbinder, and the following is its core code description.
The first is Bindmodel (ControllerContext controllercontext, Modelbindingcontext BindingContext) The method is defined in the Imodelbinder interface, is its core function to turn client data into the type we want to model.
public virtual void Updatefrom (BindingContext bindingcontext)
{
foreach (Var property in BindingContext.Target.GetType ()). GetProperties ())
{
Try
{
foreach (var binder in Propertybinders)
{
Binder. Bind (property, BindingContext);
}
}
catch (Exception Exception)
{
if (exception. InnerException is FormatException | |
exception. InnerException is IndexOutOfRangeException)
{
String key = Buildkeyformodelstate (property, Bindingcontext.objectprefix);
Bindingcontext.addmodelerror (Key, Bindingcontext.attemptedvalue, "Invalid value for {0}". With (property. Name));
BindingContext.ModelStateDictionary.SetModelValue (Key, New Valueproviderresult (Bindingcontext.attemptedvalue, Bindingcontext.attemptedvalue, CultureInfo.CurrentCulture));
}
else if (exception is validationexception)
{
String key = Buildkeyformodelstate (property, Bindingcontext.objectprefix);
Bindingcontext.addmodelerror (Key, Bindingcontext.attemptedvalue, exception. message);
BindingContext.ModelStateDictionary.SetModelValue (Key, New Valueproviderresult (Bindingcontext.attemptedvalue, Bindingcontext.attemptedvalue, CultureInfo.CurrentCulture));
}
else if (exception. InnerException is validationexception)
{
String key = Buildkeyformodelstate (property, Bindingcontext.objectprefix);
Bindingcontext.addmodelerror (Key, Bindingcontext.attemptedvalue, exception. Innerexception.message);
BindingContext.ModelStateDictionary.SetModelValue (Key, New Valueproviderresult (Bindingcontext.attemptedvalue, Bindingcontext.attemptedvalue, CultureInfo.CurrentCulture));
}
Else
{
Throw
}
}
}
if (!bindingcontext.modelstatedictionary.isvalid)
{
throw new Validationexception ("Bind Failed". Modelstatedictionary for errors ");
}
}