0

I have a typical master details view and I need to perform remote validation on the Name property of my BarViewModel.

My view models:

public class FooViewModel
{
     public IEnumerable<BarViewModel> Bars { get; set; }
}

public class BarViewModel
{
    [Required]
    [Remote("CheckName", "Foo")]
    public string Name { get; set }
}

Controller:

public class FooController
{
     public ActionResult Edit()
     {
          var viewModel = new FooViewModel
          { 
              Bars = new List<BarViewModel> { new BarViewModel() } 
          };
          return View(viewModel);
     }

     // For remote validation
     public ActionResult CheckName(/*[Bind(Prefix = "???")] */string name)
     {
          // Parameter binding failed
     }
}

FooViewModel Edit view:

@model FooViewModel

@using (Html.BeginForm())
{
    @Html.EditorFor(m => m.Bars)
}

BarViewmodel EditorTemplate:

@model BarViewModel

<div class="form-group">
    @Html.LabelFor(m => m.Name, new { @class = "control-label col-md-2 })
    <div class="col-md-10">
        @Html.EditorFor(m => m.Name, new { htmlAttributes = new { @class = "form-control" } })
        @HtmlValidationMessageFor(m => m.Name, string.Empty, new { @class = "text-danger" })
    </div>
</div>

The problem is when BarViewModel.Name is submitted for remote validation, the name parameter in the CheckName method always returns null. I have tried including the Bind attribute with Prefixes such as Bars and Bars[0] but the name parameter is still null. Can someone help?

rexcfnghk
  • 14,435
  • 1
  • 30
  • 57
  • I have previously reported reported this as a bug on Codeplex (refer [http://stackoverflow.com/questions/27513472/remote-validation-for-list-of-models/27517407#27517407](http://stackoverflow.com/questions/27513472/remote-validation-for-list-of-models/27517407#27517407)) –  Mar 04 '15 at 03:46

1 Answers1

0

Fixed it by using the BindAttribute:

public class FooController
{
     public ActionResult Edit()
     {
          var viewModel = new FooViewModel
          { 
              Bars = new List<BarViewModel> { new BarViewModel() } 
          };
          return View(viewModel);
     }

     // For remote validation
     public ActionResult CheckName([Bind(Prefix = "Bars[0].Name")] string name)
     {
          // Perform remote validation
     }
}
rexcfnghk
  • 14,435
  • 1
  • 30
  • 57