【问题标题】:Client side validation not working on Bootstrap modal on MVC View客户端验证不适用于 MVC 视图上的 Bootstrap 模式
【发布时间】:2015-02-18 20:06:48
【问题描述】:

我有一个以表格形式列出所有国家/地区的页面,并且视图具有如下模型:

@model IEnumerable<Country>

在同一页面上,我有一个链接,允许用户通过模式弹出窗口(在该页面中定义)创建新国家/地区

<a operation="add" id="btnNewCountry" data-toggle="modal" data-target="#myModal" href="#">Add New Country</a>

模型弹出 sn-p 如下所示:

<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.ValidationMessageforRequired)上应用客户端验证作为页面模式的“添加新国家”弹出窗口(IEnumerable)与模式弹出窗口(仅适用于单个国家对象)不同

请帮忙!!

【问题讨论】:

  • 你为什么有&lt;label for="module-text"&gt;?您的控件名为name!创建一个包含IEnumerable&lt;Country&gt; CountriesCountry NewCountry 属性的视图模型,以便您可以使用强类型帮助器将表单绑定到NewCountry 的属性并回发您的模型
  • 谢谢斯蒂芬..让我试试..我会尽快回复结果
  • 非常感谢,一个绝对的解决方案..不知道我怎么想不到那个方向。
  • 我看到的另一个问题是,如果有两个字段,并且我发布表单时没有在其中任何一个中输入任何内容,它会显示两个字段的 ValidationMessage,如果我在任何一个字段中输入值其中,它发布表单而不提示其他仍然为空白的字段的消息??
  • @CuriousBuddy,您需要发布更新后的代码或提出新问题(下次发布消息时,请单击“帮助”按钮)

标签: c# asp.net-mvc client-side-validation


【解决方案1】:

首先,您需要确保已将客户端验证框架包含到您的捆绑包中:

bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                    "~/Scripts/jquery-{version}.js",
                    "~/Scripts/jquery.validate.js",
                    "~/Scripts/jquery.validate.unobtrusive.js","));

然后您可以像这样在您的属性上使用 [Required] 注释:

[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 查询。

【讨论】:

  • 如果这不起作用 - 您能否检查您的浏览器控制台以查看页面上是否有任何脚本错误?
  • 我知道上面的方法,问题是我页面上的模型是 IEnumerable 所以我不能像那样绑定 CountryName
  • 然后你可以绑定它,方法是:@Html.TextBoxFor(x => x.Country.Name, new{ required=""})
猜你喜欢
  • 1970-01-01
  • 2011-02-06
  • 1970-01-01
  • 2016-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多