客户端验证在 MVC 视图上的引导模式上不起作用
本文关键字:模式 不起作用 客户端 MVC 视图 验证 | 更新日期: 2023-09-27 18:34:42
我有一个页面,以表格形式列出所有国家/地区,视图的模型如下:
@model IEnumerable<Country>
在同一页面上,我有一个链接,允许用户通过模式弹出窗口(在该页面
中定义(创建新的国家/地区
<a operation="add" id="btnNewCountry" data-toggle="modal" data-target="#myModal" href="#">Add New Country</a>
模型弹出代码段如下所示:
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-hidden="true">
@using (Html.BeginForm("ManageCountry", "Admin", FormMethod.Post, new { enctype ="multipart/form-data" }))
{
<label for="module-text">Country Name</label>
<input type="text" id="txtName" name="name" />
<button type="submit" class="btn btn-primary">Save changes</button>
}
用户按下提交按钮后,控件将快速到达控制器操作。
现在的挑战是我无法弄清楚如何在"添加新国家/地区"弹出窗口上的 CountryName 文本框(类似于 @Html.ValidationMessagefor 和 Required(上应用客户端验证,因为页面的模式(是 IEnumerable(不同于模式弹出窗口(仅适用于单个国家/地区对象(
请帮忙!!
首先,您需要确保已将客户端验证框架包含在捆绑包中:
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js",
"~/Scripts/jquery.validate.js",
"~/Scripts/jquery.validate.unobtrusive.js","));
然后,您可以在您的属性上使用 [必需] 注释,如下所示:
[Required]
public string CountryName {get; set;}
现在您可以使用:
@Html.ValidationMessageFor(x => x.Model.CountryName)
以在视图中显示错误消息。
编辑:
如果浏览器支持 HTML5,你也可以像这样使用 'required=" ':
<input type="text" name="CountryName" required="">
编辑:
根据您的评论,我建议您使用ViewModels。不需要映射的最简单方法是制作如下所示的 ViewModel:
[Required]
public List<Country> Countires { get; set; }
在控制器中,您可以将数据绑定到 ViewModel,如下所示:
//This is the call, that returns an IEnumerable
var countries = _repository.GetCountries().ToList();
var viewModel = new ViewModel(){
Countries = countries,
}
这样,您就不会直接在视图中使用 EF 查询。