2017-03-07 69 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" }) 

希望這有助於...