我正在使用MVC自定义验证服务器端,因为我必须使用多个自定义属性。 我想实现接口ValidatableObject,因为我认为它比编写多个自定义属性更简单。
强制ValidationContext我要使用自定义模型绑定器,并且我遵循David Haney在他的文章中的说明 Trigger IValidatableObject.Validate When ModelState.IsValid is false
所以我放入了global.asax
ModelBinderProviders.BinderProviders.Clear();
ModelBinderProviders.BinderProviders.Add(new ForceValidationModelBinderProvider());
然后在课堂上
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
using System.Web.Mvc;
/// <summary>
/// A custom model binder to force an IValidatableObject to execute the Validate method, even when the ModelState is not valid.
/// </summary>
public class ForceValidationModelBinder : DefaultModelBinder
{
protected override void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
base.OnModelUpdated(controllerContext, bindingContext);
ForceModelValidation(bindingContext);
}
private static void ForceModelValidation(ModelBindingContext bindingContext)
{
// Only run this code for an IValidatableObject model
IValidatableObject model = bindingContext.Model as IValidatableObject;
if (model == null)
{
// Nothing to do
return;
}
// Get the model state
ModelStateDictionary modelState = bindingContext.ModelState;
// Get the errors
IEnumerable<ValidationResult> errors = model.Validate(new ValidationContext(model, null, null));
// Define the keys and values of the model state
List<string> modelStateKeys = modelState.Keys.ToList();
List<ModelState> modelStateValues = modelState.Values.ToList();
foreach (ValidationResult error in errors)
{
// Account for errors that are not specific to a member name
List<string> errorMemberNames = error.MemberNames.ToList();
if (errorMemberNames.Count == 0)
{
// Add empty string for errors that are not specific to a member name
errorMemberNames.Add(string.Empty);
}
foreach (string memberName in errorMemberNames)
{
// Only add errors that haven't already been added.
// (This can happen if the model's Validate(...) method is called more than once, which will happen when there are no property-level validation failures)
int index = modelStateKeys.IndexOf(memberName);
// Try and find an already existing error in the model state
if (index == -1 || !modelStateValues[index].Errors.Any(i => i.ErrorMessage == error.ErrorMessage))
{
// Add error
modelState.AddModelError(memberName, error.ErrorMessage);
}
}
}
}
}
/// <summary>
/// A custom model binder provider to provide a binder that forces an IValidatableObject to execute the Validate method, even when the ModelState is not valid.
/// </summary>
public class ForceValidationModelBinderProvider : IModelBinderProvider
{
public IModelBinder GetBinder(Type modelType)
{
return new ForceValidationModelBinder();
}
}
效果很好...... 但问题来了...... 我还要在这个活页夹中添加双重和双重的特定行为?键入以此格式验证号码1.000.000,000所以我正在查看Reilly和Haack的这些资源 https://gist.github.com/johnnyreilly/5135647
using System;
using System.Globalization;
using System.Web.Mvc;
public class CustomDecimalModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
ModelState modelState = new ModelState { Value = valueResult };
object actualValue = null;
try
{
//Check if this is a nullable decimal and a null or empty string has been passed
var isNullableAndNull = (bindingContext.ModelMetadata.IsNullableValueType &&
string.IsNullOrEmpty(valueResult.AttemptedValue));
//If not nullable and null then we should try and parse the decimal
if (!isNullableAndNull)
{
actualValue = double.Parse(valueResult.AttemptedValue, NumberStyles.Any, CultureInfo.CurrentCulture);
}
}
catch (FormatException e)
{
modelState.Errors.Add(e);
}
bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
return actualValue;
}
}
然后正如Haney的评论所示,我已经用global.asax这样的方式用CustomModelBinder替换了默认的DecimalModelBinder
ModelBinders.Binders.Remove(typeof(double));
ModelBinders.Binders.Remove(typeof(double?));
ModelBinders.Binders.Add(typeof(double?), new CustomDecimalModelBinder());
ModelBinders.Binders.Add(typeof(double), new CustomDecimalModelBinder());
但我无法理解为什么.. CustomDecimalModelBinder不会触发...... 所以目前我的工作是在global.asax中评论上面的第4行 并且在自定义的ModelBinder类中添加BindModel的覆盖方式以接受double和double?在它 - 它的文化
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
//if (bindingContext.ModelName == "commercialQty")
if (bindingContext.ModelType == typeof(double?) || bindingContext.ModelType == typeof(double))
{
ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
ModelState modelState = new ModelState { Value = valueResult };
object actualValue = null;
try
{
//Check if this is a nullable decimal and a null or empty string has been passed
var isNullableAndNull = (bindingContext.ModelMetadata.IsNullableValueType &&
string.IsNullOrEmpty(valueResult.AttemptedValue));
//If not nullable and null then we should try and parse the decimal
if (!isNullableAndNull)
{
actualValue = double.Parse(valueResult.AttemptedValue, NumberStyles.Any, CultureInfo.CurrentCulture);
}
}
catch (FormatException e)
{
modelState.Errors.Add(e);
}
bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
return actualValue;
}
else
{
return base.BindModel(controllerContext, bindingContext);
}
}
通过这种方式,我的customValidation的ValidationContext可以工作,我还设法以自定义方式验证双重类型
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var results = new List<ValidationResult>();
var fieldPreliminaryCostNum = new[] { "preliminaryCostNum" };
var fieldPreliminaryCostAmount = new[] { "preliminaryCostAmount" };
var fieldPreliminaryVoucherNum = new[] { "preliminaryVoucherNum" };
var fieldCodiceIva = new[] { "codiceIva" };
var fieldContoRicavi = new[] { "contoRicavi" };
var fieldContoAnticipi = new[] { "contoAnticipi" };
//per la obbligatorietà di preliminary cost num, preliminary voucher num e preliminary cost amount è sufficiente
//il flag additional oppure occorre anche verificare che il voucher type code sia final?
if (flagAdditional == BLCostanti.fAdditional && preliminaryCostNum == null)
{
results.Add(new ValidationResult(BLCostanti.labelCosto + "preliminaryCostNum ", fieldPreliminaryCostNum));
}
if (flagAdditional == BLCostanti.fAdditional && preliminaryCostAmount == null)
{
results.Add(new ValidationResult(BLCostanti.labelCosto + "preliminaryCostAmount ", fieldPreliminaryCostAmount));
}
if (flagAdditional == BLCostanti.fAdditional && preliminaryVoucherNum == null)
{
results.Add(new ValidationResult(BLCostanti.labelCosto + "preliminaryVoucherNum ", fieldPreliminaryVoucherNum));
//inoltre il preliminary deve essere approvato!
if (! BLUpdateQueries.CheckPreliminaryVoucherApproved(preliminaryVoucherNum) )
{
results.Add(new ValidationResult(BLCostanti.labelCosto + "preliminaryVoucherNum non approvato", fieldPreliminaryVoucherNum));
}
}
if (costPayReceiveInd == BLCostanti.attivo && String.IsNullOrWhiteSpace(codiceIva))
{
//yield return new ValidationResult("codiceIva obbligatorio", fieldCodiceIva);
results.Add(new ValidationResult(BLCostanti.labelEditableFields + "codiceIva ", fieldCodiceIva));
}
if ((sapFlowType == BLCostanti.girocontoAcquisto || sapFlowType == BLCostanti.girocontiVendita)
&& String.IsNullOrWhiteSpace(contoRicavi))
{
results.Add(new ValidationResult(BLCostanti.labelEditableFields + "conto Ricavi ", fieldContoRicavi));
}
if ((sapFlowType == BLCostanti.girocontoAcquisto || sapFlowType == BLCostanti.girocontiVendita)
&& String.IsNullOrWhiteSpace(contoAnticipi))
{
results.Add(new ValidationResult(BLCostanti.labelEditableFields + "conto Anticipi ", fieldContoAnticipi));
}
return results;
}
欢迎任何更好的主意!