如何根据某些条件向模型类添加属性 [英] How Can I Add Attributes To Model Class Based On Some Conditions
本文介绍了如何根据某些条件向模型类添加属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
亲爱的所有人,
我想根据某些条件为模型类属性添加属性
$ b $例如:
假设以下EmployeeModel类:
Dear All,
I want to add attributes to model class properties based on some conditions
example:
Suppose the following EmployeeModel Class:
public class EmployeeModel
{
public int EmployeeId { get; set; }
[Required]
public string EmployeeName { get; set; }
}
我想根据某些条件在EmployeeName上添加Required属性。
我该如何实现?
I want to add the Required attribute on EmployeeName Based on Some Condition.
How can i implement that?
推荐答案
这是更新后的代码
< br $> b $ b
班级档案
Here is the updated code
Class file
public class ConditionalRequired : ValidationAttribute, IClientValidatable
{
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var mcvrTwo = new ModelClientValidationRule();
mcvrTwo.ValidationType = "contactnovalid";
mcvrTwo.ErrorMessage = "Contact No is not valid.";
mcvrTwo.ValidationParameters.Add
("contactnoregex", @"\b\d{10}\b");
return new List<ModelClientValidationRule> { mcvrTwo };
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var obj = validationContext.ObjectInstance as Customer;
if (obj.CustomerID == 1)
{
return ValidationResult.Success;
}
return new ValidationResult("Contact No is not valid");
}
}
CSHTML文件
CSHTML file
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="~/Scripts/MicrosoftAjax.js"></script>
<script type="text/javascript">
.validator.addMethod( contactnovalid, function (value,element,contactnoregex){
var patt = new RegExp (contactnoregex);
if (patt.test(value) )
return true ;
return false ;
});
.validator.addMethod("contactnovalid", function (value, element, contactnoregex) { var patt = new RegExp(contactnoregex); if (patt.test(value)) return true; return false; });
.validator.unobtrusive.adapters.add( contactnovalid,[ contactnoregex], function (options){
options.rules [ contactnovalid] = options.params.contactnoregex;
options.messages [ contactnovalid] = options.message;
});
< / script>
.validator.unobtrusive.adapters.add("contactnovalid", ["contactnoregex"], function (options) { options.rules["contactnovalid"] = options.params.contactnoregex; options.messages["contactnovalid"] = options.message; }); </script>
这篇关于如何根据某些条件向模型类添加属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文