【问题标题】:@Html.DropDownListFor not populating with validation element@Html.DropDownListFor 未填充验证元素
【发布时间】:2017-07-27 15:37:30
【问题描述】:

我在 Studio 2013 中有一个基于 C# 的 MVC 项目。

我在网页上有许多使用 razor 语法的字段,其中一些只是常规的 @Html.EditorFor(),类为 @class = "form-control",其他是 @Html.DropDownListFor()

我有一个模型可以让我为表单验证添加数据注释。我正在使用实体框架从 SQL 中引入我的地区,并将这些显示为下拉列表。这一切都很好,这纯粹是显示我拥有的验证消息的问题。

请看一下我用来创建这些的以下代码示例。

这是我的模型...

namespace MySystem.Models
{
    [MetadataType(typeof(CRecord_Buddy))]
    public partial class CRecord
    {

     // properties used to pull back and display the name etc instead on an   id in dropdown boxes.

    [Required(ErrorMessage = "Select District.")]
    public string DistrictName { get; set; }


 public class CRecord_Buddy
    {
        [Required(ErrorMessage = "Please enter a Surname.")]
        public string Surname { get; set; }

        ...
    }
 }

}

我的 create.cshtml 页面如下所示...

//code for Surname 
 @Html.EditorFor(model => model.client.Surname, new { htmlAttributes = new { @class = "form-control" } })
 @Html.ValidationMessageFor(model => model.client.Surname, "", new { @class = "text-danger" })
 @Html.ValidationMessage("Surname", "*", new { @class = "text-danger" })

//code for district
 @Html.DropDownListFor(model => model.client.District, new SelectList(Model.allDistricts, "ID", "District1", 1), "- Select District -")
 @Html.ValidationMessage("DistrictName", "*", new { @class = "text-danger" })
 @Html.ValidationMessageFor(model => model.client.District, "", new { @class = "text-danger" })

下面是验证开始时显示的图像...

从上面的图片可以看出,@Html.EditorFor 项的验证工作正常,而@Html.Dropdownlistfor 项则不行。在填充验证方面,它们的设置相同,但我似乎无法让下拉列表项正常工作。

欢迎提出任何建议。

【问题讨论】:

标签: c# html asp.net-mvc validation


【解决方案1】:

必需的属性在 DistrictName 上,而不是在 District 上。 这就是验证结果不可见的原因。

【讨论】:

    【解决方案2】:

    尝试如下定义:

    //code for district
    @Html.DropDownListFor(model => model.client.DistrictName, new SelectList(Model.allDistricts, 
        "ID", "District1", 1), "- Select District -")
    @Html.ValidationMessage("DistrictName", "*", new { @class = "text-danger" })
    @Html.ValidationMessageFor(model => model.client.DistrictName, "", new { @class = "text-danger" })
    

    希望这会有所帮助...

    【讨论】:

      猜你喜欢
      • 2019-04-19
      • 2018-04-13
      • 2019-07-11
      • 2016-10-08
      • 1970-01-01
      • 1970-01-01
      • 2011-09-19
      • 2016-04-28
      • 1970-01-01
      相关资源
      最近更新 更多