【问题标题】:MVC3 Project set StringLength validation value from another propertyMVC3 项目从另一个属性设置 StringLength 验证值
【发布时间】:2013-10-22 20:34:33
【问题描述】:

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

【问题讨论】:

标签: c# asp.net-mvc razor


【解决方案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; }
    .....

【讨论】:

    【解决方案2】:

    试试这个

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

    或使用 MaximumLength 并查看此链接以获取 String Length Attribute

    【讨论】:

    • 这如何帮助我将最大长度设置为数据库中的动态值?您只是将其设置为 50?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-26
    • 1970-01-01
    • 2015-01-02
    • 1970-01-01
    • 2021-06-21
    相关资源
    最近更新 更多