Remote Validation for LIST of MODELs

∥☆過路亽.° 提交于 2019-11-26 14:44:04

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: 'someone@somewhere.com' },
  ...

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: 'someone@somewhere.com' },

and will correctly bind to the method.

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