Search code examples
asp.net-mvcvalidationasp.net-mvc-4remote-validation

MVC Remote Attribute Issue


I setup a remote validator in MVC to be sure that a company doesn't already exist when creating or editing a company on my page. Here is the model:

public class AdminCompany
{
    public int CompanyId { get; set; }

    [Display(Name = "Company Name")]
    [Required(ErrorMessage = "Company Name is required")]
    [Remote("DoesCompanyExist", "Ajax", HttpMethod = "POST", ErrorMessage="This company already exists.")]
    public string CompanyName { get; set; }

    public string PortalsString { get; set; }
}

And here is the DoesCompanyExist function:

[HttpPost]
[AjaxOnly]
public JsonResult DoesCompanyExist(string CompanyName)
{
    var companies = new Companys();
    companies.GetBySqlStatement("SELECT CompanyName FROM Company WHERE CompanyName='{0}'", CompanyName);

    return Json(companies.Count == 0);
}

Everything is working just fine except for one issue. On my edit page, if the user goes into a company's edit page, then just saves it without changing anything, my remote validator is triggering a validation error. The reason is because the company does, in fact, already exist in the database, however, my remote validator doesn't realize that its the same record being modified.

Is there some kind of work around to this? Ideally, it would be nice if I could somehow pass the CompanyId onto my remote validator. That way I could exclude that ID from my SELECT statement.


Solution

  • Check out AdditionalFields parameter for RemoteAttribute. This will allow you to, as you described, supply another field value (such as an entity ID) that can be used to validate edits (versus creates).