【问题标题】:How to add @Html.ValidationMessageFor for each item in a collection?如何为集合中的每个项目添加@Html.ValidationMessageFor?
【发布时间】:2014-07-27 17:27:47
【问题描述】:

如何为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 进行客户端验证。任何你应该做的事情,比如这个建议或提示,示例代码都会很棒。谢谢。

【问题讨论】:

    标签: c# javascript asp.net asp.net-mvc-4 unobtrusive-validation


    【解决方案1】:

    实际上,使用 Javascript 填充 View 并不是 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; }
    }
    

    现在是视图的代码:

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

    这将呈现必要的标签 - 当然还有验证消息位。但是,也可以使用

    将所有错误消息合并到一个位置
    @Html.ValidationSummary()
    

    如果您真的希望仅在单击按钮后才显示内容,请考虑使用局部视图并加载该视图。这比尝试使用 javascript 创建所有必要的标签和属性进行验证要好得多。

    问候,

    弗兰克

    【讨论】:

    • 这行不通!它不验证列表中的模型
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    相关资源
    最近更新 更多