Remote Validation for LIST of MODELs

You have not posted your code for the model or controller, but assuming you have a RemoteAttribute applied to property Username, for example

public class MyModel
{
  [Remote("IsValidUserName", "Person")]
  public string Username { get; set; }
}

with a method in PersonController

public JsonResult IsValidUserName(string Username)
{
  ....
}

and the view

@model List<Person>
...
@for (var i = 0; i < Model.Count; i++)
{
  @Html.EditorFor(m => m[i].Username)                           
}

This will generate html such as

<input name="[0].UserName" ... />
<input name="[1].UserName" ... />

Unfortunately the remote method in jquery-validate posts back the name and value of the element so that the ajax call looks like

$.ajax({
  url: '/Person/IsValidUserName',
  data: { [0].UserName: '[email protected]' },
  ...

which will not bind.

I have reported this as an issue at Codeplex with a possible solution. In the meantime you can modify the remote method in jquery-validate.js file as follows

remote: function(value, element, param) {
  ....
  var data = {};
  // data[element.name] = value;
  data[element.name.substr(element.name.lastIndexOf(".") + 1)] = value; // add this

This will strip the prefix so that the posted data is

 data: { UserName: '[email protected]' },

and will correctly bind to the method.

Leave a Comment