3

I have list of models and want to perform remote validation.

Model:

[System.Web.Mvc.Remote("Method", "Controller", HttpMethod = "POST", AdditionalFields = "prop2,prop3", ErrorMessage = "Error")]
 public string prop1 { get; set; }

The name generated by MVC for each elements are like below:

<input type='text' name='test[0].prop1' />

Because of this, values are not binding to the parameters. I took help from this Post. Now I am getting the value for 'prop1' but still 'prop2' and 'prop3' are not getting bound.

Edit: I am using BeginCollectionItem to render the list elements.

Any help or suggestion would be great.

Thanks in advance.

Jayakrishnan
  • 4,232
  • 2
  • 23
  • 35

3 Answers3

2

If the remote method takes an object (as parameter) that holds its sub-items, they should be mapped automatically, for instance:

public class Stuff
{
  public List<Item> Items { get; set; }
}

public class Item
{
  [Remote(action:"Validate", controller: "Account", 
      HttpMethod = "POST", 
      ErrorMessage = "Error",
      AdditionalFields = "Prop2,Prop3")]
  public string Prop1 { get; set; }

  public string Prop2 { get; set; }
  public string Prop3 { get; set; }
}
@using (Html.BeginForm("Index", "Account"))
{
  for (int i = 0; i < Model.Items.Count; i++)
  {
    @Html.TextBoxFor(m => Model.Items[i].Prop1)
    @Html.TextBoxFor(m => Model.Items[i].Prop2)
    @Html.TextBoxFor(m => Model.Items[i].Prop3)
  }
}

enter image description here

Yom T.
  • 8,760
  • 2
  • 32
  • 49
0

By default all model properties are null except main property,

If you have another propeties to validate Bind Include them.

public ActionResult CheckThings([Bind(Include = "prop2,prop3")] Model model)
{
.....
}

If your action method dosnt accept model and you pass seperated fields to it, use

public ActionResult CheckThings([Bind(Prefix = "Prop1OrSomethigElse")]string prop1, [Bind(Prefix = "Prop2OrSomethigElse")]string prop2, [Bind(Prefix = "Prop3OrSomethigElse")]string prop3)
{
.....
}
NaDeR Star
  • 647
  • 1
  • 6
  • 13
0

I have taken idea from this post and fixed it by modifying the remote method in jquery-validate.js file as below:

remote: function(value, element, param) {
 ....
  param = typeof param === "string" && {url:param} || param;
  ....

  for (var property in param.data) {
    if (param.data.hasOwnProperty(property)) {
        param.data[property.substr(property.lastIndexOf(".") + 1)] = param.data[property];
      }
    }
   //ajax call
Jayakrishnan
  • 4,232
  • 2
  • 23
  • 35