【问题标题】:Parameters binding in remote validation远程验证中的参数绑定
【发布时间】:2015-03-04 11:42:19
【问题描述】:

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

我的视图模型:

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)
}

BarViewmodelEditorTemplate:

@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提交远程验证时,CheckName方法中的name参数总是返回null。我尝试将Bind 属性与Prefixes 包括在一起,例如BarsBars[0],但name 参数仍然是null。有人可以帮忙吗?

【问题讨论】:

标签: c# asp.net-mvc


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-02
    • 2017-04-09
    • 1970-01-01
    • 2022-11-03
    • 2012-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多