【问题标题】:How can I make the Required attribute for my custom DropDownList editor template operate client side?如何使自定义 DropDownList 编辑器模板的 Required 属性在客户端运行?
【发布时间】:2012-12-29 15:39:37
【问题描述】:

我有一个 DropDownLists 的编辑器模板,它标有如下属性:

[AttributeUsage(AttributeTargets.Property)]
public class DropDownListAttribute : UIHintAttribute
{
    public string SelectListName { get; set; }
    public DropDownListAttribute(string selectListName)
        : base("DropDownList", "MVC", selectListName)
    {
        SelectListName = selectListName;
    }
}

而且它本身看起来是这样的:

@using Comair.RI.UI.Core
@{
    var list = this.GetModelSelectList();
    var listWithSelected = new SelectList(list.Items, list.DataValueField, list.DataTextField, Model);
}
@Html.DropDownListFor(m => Model, listWithSelected, " - select - ")

我的问题是它只验证服务器端,这对于用户解决所有客户端验证非常烦人,只是提交并获得一个新的、令人惊讶的服务器端验证。

【问题讨论】:

  • 你能添加你的模型的代码
  • @SławomirRosiek 这应该是什么意思?这是适用于任何模型的一般问题。
  • 对我来说它有效 - 您是否只对那个控件有问题,或者可能对所有客户端验证器有问题?

标签: asp.net-mvc asp.net-mvc-4 data-annotations asp.net-mvc-viewmodel


【解决方案1】:

如果您的客户端验证不起作用,可能是由以下原因之一引起的:

  1. 您的 web.config 没有该条目:

    &ltapp设置> 设置>
  2. 您忘记添加验证脚本:

  3. 您的控件没有被Html.BeginFormAjax.BeginForm包围

  4. 如果您使用,更新到 ASP.NET MVC 4 后,客户端验证可能会在 EditorFor 中停止工作:

    @Html.DropDownListFor(m => Model, listWithSelected, " - select - ")
    

    Model 替换为m 应该可以解决问题:

    @Html.DropDownListFor(m => m, listWithSelected, " - select - ")
    

【讨论】:

  • 我的所有其他客户端验证都有效。我的问题是只有我的DropDownList 编辑器模板不验证客户端。
  • 我添加了另一种可能性。
【解决方案2】:

设置所需的类

@Html.DropDownListFor(m => Model, listWithSelected, " - select - ", new { @class='required' })

ASP MVC 3: How can I do Client side Validation on a Select List?

【讨论】:

  • 可爱,除了默认消息只是“此字段是必需的”。而不是“需要 {0} 字段”。查找是否将验证消息内联放置,但如果将它们分组在某个“窗口”某处,则不是那么酷。
猜你喜欢
  • 1970-01-01
  • 2016-01-12
  • 2014-11-27
  • 2011-04-19
  • 2023-04-07
  • 1970-01-01
  • 1970-01-01
  • 2012-10-11
  • 2021-04-15
相关资源
最近更新 更多