以编程方式更改验证范围(MVC3 ASP.NET)
假设我有这个视图模型:
public class MyModel { [Range(0, 999, ErrorMessage = "Invalid quantity")] public int Quantity { get; set; } }
现在,对于此模型的特定实例,有效值的范围会发生变化:有些值可能不是0,有些可能不会高于5.有效范围的最小/最大值来自数据库,并且可以随时更改。
如何更改即时更改RangeAttribute的最小/最大属性? 或者验证我的方案的最佳方法是什么?
沿着这条线的东西可能会更多你的后...
视图模型:
public class ViewModel
{
public DateTime MinDate {get; set;}
public DateTime MaxDate {get; set;}
[DynamicRange("MinDate", "MaxDate", ErrorMessage = "Value must be between {0} and {1}")]
public DateTime Date{ get; set; }
}
图书馆课或其他地方:
public class DynamicRange : ValidationAttribute, IClientValidatable
{
private readonly string _minPropertyName;
private readonly string _maxPropertyName;
public DynamicRange(string minPropName, string maxPropName)
{
_minPropertyName = minPropName;
_maxPropertyName = maxPropName;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var minProperty = validationContext.ObjectType.GetProperty(_minPropertyName);
var maxProperty = validationContext.ObjectType.GetProperty(_maxPropertyName);
if(minProperty == null)
return new ValidationResult(string.Format("Unknown property {0}", _minPropertyName));
if (maxProperty == null)
return new ValidationResult(string.Format("Unknown property {0}", _maxPropertyName));
var minValue = (int) minProperty.GetValue(validationContext.ObjectInstance, null);
var maxValue = (int) maxProperty.GetValue(validationContext.ObjectInstance, null);
var currentValue = (int) value;
if (currentValue <= minValue || currentValue >= maxValue)
{
return new ValidationResult(string.Format(ErrorMessage, minValue, maxValue));
}
return null;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ValidationType = "dynamicrange",
ErrorMessage = ErrorMessage
};
rule.ValidationParameters["minvalueproperty"] = _minPropertyName;
rule.ValidationParameters["maxvalueproperty"] = _maxPropertyName;
yield return rule;
}
来自:MVC动态值的不显眼范围验证
我认为你最好的选择可能是为你的特定模型( MyModel
)实现一个自定义模型MyModel
。 你可以拥有这样的东西:
public class MyModel
{
public int Quantity { get; set; }
} // unchanged Model
public class MyViewModel
{
public MyModel myModel { get; set; }
public int QuantityMin { get; set; }
public int QuantityMax { get; set; }
}
然后您可以设置这些值,并在您的自定义模型联编程序中,您可以将myModel.Quantity
属性与QuantityMin
和QuantityMax
属性进行比较。
例
型号 :
public class QuantityModel
{
public int Quantity { get; set; }
}
ViewMode :
public class QuantityViewModel
{
public QuantityModel quantityModel { get; set; }
public int QuantityMin { get; set; }
public int QuantityMax { get; set; }
}
自定义模型绑定器 :
public class VarQuantity : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
int MinValue = Convert.ToInt32(bindingContext.ValueProvider.GetValue("QuantityMin").AttemptedValue);
int MaxValue = Convert.ToInt32(bindingContext.ValueProvider.GetValue("QuantityMax").AttemptedValue);
int QuantityValue = Convert.ToInt32(bindingContext.ValueProvider.GetValue("quantityModel.Quantity").AttemptedValue);
if (!(QuantityValue >= MinValue && QuantityValue <= MaxValue))
bindingContext.ModelState.AddModelError("Quantity", "Quantity not between values");
return bindingContext.Model;
}
}
注册自定义模型绑定器 :
ModelBinders.Binders.Add(typeof(QuantityViewModel), new VarQuantity());
测试控制器操作方法 :
public ActionResult Quantity()
{
return View();
}
[HttpPost]
public string Quantity(QuantityViewModel qvm)
{
if (ModelState.IsValid)
return "Valid!";
else
return "Invalid!";
}
测试查看代码 :
@model MvcTest.Models.QuantityViewModel
<h2>Quantity</h2>
@using (Html.BeginForm())
{
@Html.Label("Enter Your Quantity: ")
@Html.TextBoxFor(m => m.quantityModel.Quantity)
<br />
@Html.Label("Quantity Minimum: ")
@Html.TextBoxFor(m => m.QuantityMin)
<br />
@Html.Label("Quantity Maximum: ")
@Html.TextBoxFor(m => m.QuantityMax)
<br /><br />
<input type="submit" value="Submit" />
}
链接地址: http://www.djcxy.com/p/30571.html
上一篇: Changing validation range programmatically (MVC3 ASP.NET)