1

I have Remote validation for Postal code field and country Id is passed to it as additional field. following is the code:

    public JsonResult IsValidPostalCodeForCountry(string CompanyPostalCode, string CompanyCountryID)
    {
        //My validation code
        return Json(true, JsonRequestBehavior.AllowGet);
    }

Model:

[PostalCodeRemoteValidation("IsValidPostalCodeForCountry", "Common", "", AdditionalFields = "CompanyCountryID")]
[Required(ErrorMessageResourceName = "valPostalcodeRqrd")]        
public string CompanyPostalCode { get; set; }


[Required(ErrorMessageResourceName = "valCountryRqrd")]
public int CompanyCountryID { get; set; }

Can the names is action parameter and names in model property be different?

Why I want this?
to call same remote validation method from different models where name of property can be different.

SurajS
  • 473
  • 7
  • 20
  • What is you actual question? –  Jul 30 '15 at 10:58
  • @StephenMuecke Check now, hope this is more clear. – SurajS Jul 30 '15 at 11:14
  • 1
    They cant be different. The `RemoteAttribute` calls a server method, passing the name and value of the property - in your case the url generated would be `/Common/IsValidPostalCodeForCountry?CompanyPostalCode=somValue&CompanyCountryID=anotherValue` The property name must match the parameter name. You will need multiple controller methods, but you could refactor out the logic to a private method (say) `private bool IsValid(string code, string ID)` so that each controller method only has one line of code - `return Json(IsValid(x, y));` –  Jul 30 '15 at 11:23
  • Thank you @StephenMuecke. But that's what I am trying to avoid. I am searching for something like [this](http://stackoverflow.com/questions/27807745/same-remote-validation-for-2-different-properties-in-a-model) – SurajS Jul 30 '15 at 11:28
  • Very fragile solution IMO. And impossible to test and debug. But why do you have different property names for something that represents the same thing. Your using a view model so why not just use consistent naming so they are all `PostalCode` and `CountryID`? –  Jul 30 '15 at 11:33
  • That's true @StephenMuecke.. But I am working on already developed large codebase.. where all the models are written already and it will be huge task to change name of properties.. – SurajS Jul 30 '15 at 13:47
  • 1
    A word of warning about the answer you linked to. I don't believe there is any guarantee that the values will be posted in the correct order so accessing `Request.Key` by indexer may break in the future. Hopefully your property names contain at least something common (e.g. contains "Code" and "ID") so that you can verify them. And creating a custom model binder would be a better solution (keeping the existing parameters) - the model binder would read the query string parameters and reset their 'names' to match the method parameters. –  Jul 30 '15 at 14:02

0 Answers0