远程验证中的参数绑定

时间:2015-03-04 02:51:51

标签: c# asp.net-mvc

我有一个典型的主要详细信息视图,我需要对Name的{​​{1}}属性执行远程验证。

我的观点模型:

BarViewModel

控制器:

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

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

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

@model FooViewModel @using (Html.BeginForm()) { @Html.EditorFor(m => m.Bars) } EditorTemplate:

BarViewmodel

问题是,当提交@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> 进行远程验证时,BarViewModel.Name方法中的name参数始终返回CheckName。我尝试将null属性与BindPrefix Bars包括在一起,但Bars[0]参数仍为name。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

使用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
     }
}