【问题标题】:How to use @Html.ValidationMessageFor for @Html.TextBox如何将@Html.ValidationMessageFor 用于@Html.TextBox
【发布时间】:2021-08-13 11:28:45
【问题描述】:

以下工作正常:

@Html.TextBoxFor(x => x.Residence.Rent, new { @class = "form-control"" })
@Html.ValidationMessageFor(x => x.Residence.Rent, null, "span")

但是需要向控制器发送一个对象列表。所以我尝试了这个:

@for(int index = 0; index < Model.ResidencesList.Count; index++)
{
    @Html.TextBox("ResidencesList[" + index + "].Rent", ResidencesList[index].Rent, new { id="", @class = "form-control"" })
    @Html.ValidationMessageFor("ResidencesList[" + index + "].Rent", null, "span")
}

将标记呈现为:

<input class="form-control" name="ResidencesList[0].Rent" type="text" value="">
<span class="field-validation-error" data-valmsg-for="ResidencesList[0].Rent" data-valmsg-replace="true">
   <span>undefined</span>
</span>

提交时验证不会触发,当我选择文本框时还会显示“未定义”消息。

【问题讨论】:

    标签: c# .net asp.net-mvc


    【解决方案1】:

    尝试替换

      @Html.TextBox("ResidencesList[" + index + "].Rent", ResidencesList[index].Rent, new { id="", @class = "form-control"" })
     @Html.ValidationMessageFor("ResidencesList[" + index + "].Rent", null, "span")
    

    @Html.TextBoxFor(model=> model.ResidencesList[index].Rent, new {  @class = "form-control"})
     @Html.ValidationMessageFor( model=> model.ResidencesList[index].Rent, "", new { @class = "text-danger" })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-27
      • 1970-01-01
      • 2012-01-30
      • 1970-01-01
      • 1970-01-01
      • 2017-07-16
      • 2020-01-11
      相关资源
      最近更新 更多