asp.net-mvc - 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){}
时,为什么我的错误信息没有显示?
解决方案
假设您的观点,我设法重新生成了您的代码:
请注意 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);
}
希望这有帮助... :)
推荐阅读
- nunit - NBuilder 和 DbContext 无效转换问题
- if-statement - 用有效的电子邮件格式替换无效的电子邮件格式
- vue.js - 如何为 Element UI 单选组上的更改设置 preventDefault
- c++ - 为什么 reinterpret_cast 不是 constexpr?
- json - 替换 JSON 树中未知位置的 JSON 对象
- javascript - 几个不同浏览器选项卡中的 Angular 和 TypeScript/javascript 单例
- python-3.x - 在 Numpy 中将一维数组转换为行或列向量
- yacc - 如何避免yacc C语法乘法与指针冲突?
- python - NUMPY:np.empty(()) 在二维数组中做了什么?
- c# - 在c#中调用对象外部方法效率更高?