Same Remote Validation for 2 different properties in a model

落爺英雄遲暮 提交于 2019-12-07 13:55:04

问题


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?


回答1:


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.

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:


Adding onto Rhumborls answer if you find his method not to work it might be because you're using forms; if this is the case you need to use the Form attribute instead of the QueryString as so.

public JsonResult ValidateContractor()
{
    // gets the name of the property being validated, e.g. "Cntrctr1"
    string fieldName = Request.Form.Keys[0];

    // gets the value to validate
    string Cntrctr = Request.Form[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);}
}


来源:https://stackoverflow.com/questions/27807745/same-remote-validation-for-2-different-properties-in-a-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!