对模型中的2个不同属性进行相同的远程验证 [英] Same Remote Validation for 2 different properties in a model
问题描述
我在模型中有2个属性Contractor1和Contractor2,如何为它们两个使用单个远程验证
I have 2 properties contractor1 and contractor2 in a model, how can I use a single remote validation for both of them
[Display(Name ="Contractor 1:")]
[Remote("ValidateContractor", "Contracts")]
public string Cntrctr1 {get; set;}
[Display(Name = "Contractor 2:")]
[Remote("ValidateContractor", "Contracts")]`enter code here`
public string Cntrctr2 {get; set;}
控制器中的远程验证功能
Remote Validation function in the Controller
public JsonResult ValidateContractor1(string Cntrctr)
{
var valid = Validations.ValidateContractor(Cntrctr);
if (!valid)
{return Json("Enter correct contractor", JsonRequestBehavior.AllowGet);}
else{return Json(true, JsonRequestBehavior.AllowGet);}
}
public static bool ValidateContractor(string CntrctrNM)
{
bool valid;
using (var entities = new CAATS_Entities())
{
var result = (from t in entities.PS_VENDOR_V
where (t.VNDR_1_NM).Equals(CntrctrNM)
select t).FirstOrDefault();
if (result != null)
{
valid = true;
}
else
{
valid = false;
}
}
return valid;
}
这不起作用.你能帮我吗?
This doesn't work. Can you please help me with this?
推荐答案
调用远程验证时,querystring键是字段的名称,例如在您的情况下/Contracts/ValidateContractor1?Cntrctr1=foo
.您需要一个更动态的解决方案.
When remote validation is called, the querystring key is the name of the field, e.g. in your case /Contracts/ValidateContractor1?Cntrctr1=foo
. You need a more dynamic solution.
执行此操作的一种方法是在ValidateContractor1
中不包含任何参数,而只是获取第一个查询字符串值.这未经测试,但可以为您工作:
One way you can do this is to not have any parameters in ValidateContractor1
and just grab the first query string value instead. This isn't tested but should work for you:
public JsonResult ValidateContractor1()
{
// gets the name of the property being validated, e.g. "Cntrctr1"
string fieldName = Request.QueryString.Keys[0];
// gets the value to validate
string Cntrctr = Request.QueryString[fieldName];
// carry on as before
var valid = Validations.ValidateContractor(Cntrctr);
if (!valid)
{return Json("Enter correct contractor", JsonRequestBehavior.AllowGet);}
else{return Json(true, JsonRequestBehavior.AllowGet);}
}
这篇关于对模型中的2个不同属性进行相同的远程验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!