如何添加@Html.集合中每个项目的ValidationMessageFor

本文关键字:项目 ValidationMessageFor 集合 @Html 何添加 添加 | 更新日期: 2023-09-27 18:15:10

如何为collection中的每个item添加@Html.ValidationMessageFor() ?说,

public class FooVm
{
  // some property
  public ICollection<BarVm> Bars { get; set; }
}
public class BarVm
{
  // some property
  [Range(1, int.Max, ErrorMessage = "Must be greater than 1")
  public float? Fox { get; set; }
}

则在view

@model namespace.here.FooVm
<div class="container"></div>
<a href="#" class="trigger">Populate</a>
<script>
$(function() {
  var i = 0;
  var populate = function() {
    var strBuilder = '<input type="text" name="Bars[i].Fox" />';
    $(".container").append(strBuilder);
    return false;
  };
  $(".trigger").click(populate);
});
</script>

一切正常。但是我如何在每个textbox中添加验证?我还在用ASP.NET MVC 4练习。我还利用unobtrusive validation进行客户端验证。任何"您应该做类似的事情"的建议或技巧、示例代码都很棒。谢谢。

如何添加@Html.集合中每个项目的ValidationMessageFor

实际上,使用Javascript来填充视图并不是MVC应该使用的方式。相反,您可以像这样呈现所有文本框:

首先是类的代码:
public class FooVm
{
    // some property
    public List<BarVm> Bars { get; set; }
    public FooVm()
    {
        // Make sure the collection exists to prevent NullReferenceException
        this.Bars = new List<BarVm>();
    }
}
public class BarVm
{
    // some property
    [Range( 1, Int32.MaxValue, ErrorMessage = "Must be greater than 1" )]
    public float? Fox { get; set; }
}
下面是View的代码:
@model WebApplication2.Models.FooVm
<h2>Sample View</h2>
@using ( Html.BeginForm( "YourAction", "YourController" ) )
{
    <div class="container">
    @for ( int i = 0; i < Model.Bars.Count; i++ )
    {
        @Html.TextBoxFor( m => m.Bars[i].Fox )
        @Html.ValidationMessageFor( m => m.Bars[i].Fox );
    }
    </div>
}

这将呈现必要的标记——当然还有validationmessage-bits。但是,也可以通过使用

将所有错误消息组合在一个地方。
@Html.ValidationSummary()

如果你真的想在点击按钮后才显示内容,可以考虑使用局部视图并加载它。这比使用javascript创建所有必要的标签和属性来验证要好得多。

问候,弗兰克