我有一个典型的主要详细信息视图,我需要对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
属性与Bind
和Prefix
Bars
包括在一起,但Bars[0]
参数仍为name
。有人可以帮忙吗?
答案 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
}
}