gpt4 book ai didi

c# - MVC3 项目从另一个属性设置 StringLength 验证值

转载 作者:太空宇宙 更新时间:2023-11-03 13:33:41 26 4
gpt4 key购买 nike

我有一个 mvc razor 页面,其中包含一个表单,其中包含从数据库动态创建的字段,即字段名称、类型(文本框等)以及 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; }

最佳答案

您可以编写自己的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; }
.....

关于c# - MVC3 项目从另一个属性设置 StringLength 验证值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19485786/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com