3

我有一个 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; }
4

2 回答 2

2

你可以自己写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; }
    .....
于 2013-10-21T07:05:16.723 回答
0

尝试这个

[StringLength(50, MinimumLength=10)]
public string Answer { get; set; }

或使用MaximumLength并查看此链接以获取字符串长度属性

于 2013-10-21T04:41:01.277 回答