首页 > 解决方案 > mvc validationMessage 在 IEnumerable 中不起作用

问题描述

我有一堂课:

public class Cust
{
    [Required(ErrorMessage ="NameField Req")]
    public string Name { get; set; }
}

我使用这个类:

public class CustModel
{
    public IEnumerable<Cust> CustList { get; set; }
}

.cshtml

@model WebApplication2.Models.CustModel

  @Html.EditorFor(m => m.CustList)
        @Html.ValidationMessageFor(val => val.CustList)

当我点击提交按钮if (ModelState.IsValid){}时,为什么我的错误信息没有显示?

标签: asp.net-mvcasp.net-mvc-validation

解决方案


假设您的观点,我设法重新生成了您的代码:

请注意 for 循环

@model MVC_SteckOverflow.Models.ViewModels.CustModel
@using MVC_SteckOverflow.Models.ViewModels

@{
    ViewBag.Title = "ValidateIenumerable";
}

<style>
    .field-validation-error {
        color:#F00;
    }
    .input-validation-error {
        border: 1px solid red;
        background-color: #f9e2e2b3;
    }
</style>

<h2>ValidateIenumerable</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>CustModel</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @for (int i = 0; i != Model.CustList.Count(); i++)
            {
                @Html.EditorFor(x => x.CustList.ToList()[i].Name)
                @Html.ValidationMessageFor(x => x.CustList.ToList()[i].Name)
            }


            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section scripts{
    @Scripts.Render("~/bundles/jqueryval")
}

根据控制器中的以下操作:

    public ActionResult ValidateIenumerable()
    {
        CustModel custModel = new CustModel {
            CustList = new List<Cust> {
                new Cust{ Name = "A"},
                new Cust{ Name = "B"},
                new Cust{ Name = "C"},
            },
        };
        return View(custModel);
    }

    [HttpPost]
    public ActionResult ValidateIenumerable(CustModel custModel)
    {

        return View(custModel);
    }

上面的代码经过测试、构建并成功运行。 在此处输入图像描述

希望这有帮助... :)


推荐阅读