我有一个mvc razor页面,其中包含一个表单,其中包含从数据库动态创建的字段,即字段名称,类型(文本框等)在db表中设置,以及StringLength
我的模型中是否有某种方法可以将字段上的StringLength设置为来自其他属性之一的值?
问题是使用QuestionModel的编辑器模板构建的,这些是QuestionModel中的相关字段;
public string QuestionTypeName { get; set; } --> ie this is like TextBox, TextArea etc and is used to create the write EditorTemplate
[RequiredIf("Required", true)]
[StringLength(<<this is where I want to use the property FieldLength>>)]
public string Answer { get; set; }
[DisplayName("Question name")]
public string Question { get; set; }
public bool Required { get; set; }
public Int32 FieldLength { get; set; }
答案 0 :(得分:1)
您可以按如下方式编写自己的Custom Validation Attribute
实施
public class CustomValidation : ValidationAttribute
{
public CustomValidation(string otherproperty)
: base("Your Error Message goes here")
{
OtherProperty = otherproperty;
}
public string OtherProperty { get; set; }
public override string FormatErrorMessage(string name)
{
return string.Format(ErrorMessageString, name, OtherProperty);
}
protected override ValidationResult IsValid(object firstobject, ValidationContext validationContext)
{
var firstValue = firstobject;
var secondValue = GetSecondObject(validationContext);
if(firstValue !=null && secondValue!=null)
{
if (//Your Condition for validation failure)
{
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
}
}
return ValidationResult.Success;
}
protected object GetSecondObject(
ValidationContext validationContext)
{
var propertyInfo = validationContext
.ObjectType
.GetProperty(OtherProperty);
if (propertyInfo != null)
{
var secondValue = propertyInfo.GetValue(
validationContext.ObjectInstance, null);
return secondValue as object;
}
return null;
}
}
用法:
public class ClassName
{
[CustomValidation("FieldLength")] // pass the property name
public string Answer { get; set; }
.....
答案 1 :(得分:0)
试试这个
[StringLength(50, MinimumLength=10)]
public string Answer { get; set; }
或使用 MaximumLength 并查看String Length Attribute
的此链接