gpt4 book ai didi

asp.net-mvc - 类 mvc 上的多个自定义验证属性

转载 作者:行者123 更新时间:2023-12-01 04:19:53 24 4
gpt4 key购买 nike

我正在创建一个示例以更好地理解。

[CustomValidator("Property1","Property2", ErrorMessage= "Error1")]
[CustomValidator("Property3","Property4", ErrorMessage= "Error1")]
public class MyViewModel
{
public string Property1 {get; set;}
public string Property2 {get; set;}
public string Property3 {get; set;}
public string Property4 {get; set;}
}

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)]
public class CustomValidator : ValidationAttribute
{
All the required stuff is written.
}

只有第二个验证器(或列表中的最后一个)被触发并忽略第一个。
我不确定这是否是这种情况的正确方法。
有什么建议?

最佳答案

如果您正在使用 Linq to SQL 为什么不尝试这样的事情

添加规则违规类来处理规则违规

public class RuleViolation
{
public string ErrorMessage { get; private set; }
public string PropertyName { get; private set; }
public RuleViolation(string errorMessage)
{
ErrorMessage = errorMessage;
}
public RuleViolation(string errorMessage, string propertyName)
{
ErrorMessage = errorMessage;
PropertyName = propertyName;
}
}

现在在你的数据课上
[Bind(Exclude="ID")]
public partial class Something
{
public bool IsValid
{
get { return (GetRuleViolations().Count() == 0); }
}

public IEnumerable<RuleViolation> GetRuleViolations()
{
if (String.IsNullOrEmpty(Name.Trim()))
yield return new RuleViolation("Name Required", "Name");
if (String.IsNullOrEmpty(LocationID.ToString().Trim()))
yield return new RuleViolation("Location Required", "LocationID");
yield break;
}

partial void OnValidate(ChangeAction action)
{
if (!IsValid)
throw new ApplicationException("Rule violations prevent saving");
}

}

并在 Controller 的更新方法中,使用 updatemodel 方法更改属性
Something something = somethingRepo.GetSomething(id);
try
{
//update something
UpdateModel(something);
somethingRepo.Save();
return RedirectToAction("Index");
}
catch
{
ModelState.AddRuleViolations(something.GetRuleViolations());
return View(something);
}

通过这种方式,您可以在数据类发生变化时向其添加规则,并将反射(reflect)在您的更新等中

关于asp.net-mvc - 类 mvc 上的多个自定义验证属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2321811/

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