2017-03-07 37 views
-1

我有一个基于C#的studio 2013中的MVC项目。@ Html.DropDownListFor不填充验证元素

我有一个使用剃刀语法的网页上的一些字段,其中一些只是常规的@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" }) 

下面是什么是影像当验证启动时显示...

enter image description here ​​

从上面的图片可以看出,对于@ Html.EditorFor项目,验证工作正常,但对于项目@ Html.Dropdownlist没有效果。这些都是建立在填充验证方面相同,但我似乎无法让dropdownlist项目正常工作。

欢迎任何建议。

+0

你可以试试这个:http://stackoverflow.com/questions/4729440/validate-a-dropdownlist- in-asp-net-mvc –

+2

属性'区'是什么? (你所显示的是一个名为'DistrictName'的) –

回答

0

必填属性为DistrictName而不是District。 这就是原因验证结果不可见。

0

尝试定义如下图所示:

//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" }) 

希望这有助于...