Same remote confirmation for two different properties in the model

I have 2 properties contractor1 and contractor2 in the model, how can I use one remote check 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 check 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 does not work. Could you help me with this?

+3


source to share


2 answers


When remote validation is called, the request key is the name of the field, eg. in your case /Contracts/ValidateContractor1?Cntrctr1=foo

. You need a more dynamic solution.

One way to do this is to have no parameters in it ValidateContractor1

and just take the first value of the query string. This is untested, 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


source


Adding to Rhumborls' answer, if you find that his method doesn't work, it might be because you are using forms; If so, you need to use the Form attribute instead of QueryString.



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);}
}

      

0


source







All Articles