0

我一直在這個問題上停留了一段時間,似乎無法找到任何有助於解決的問題。Asp.Net MVC 5 Html.DropDownList未驗證

我在編輯器模板中有一個Html.DropDownList。我在表單中使用該模板,不要爲下拉列表選擇任何內容。當我點擊提交時,我希望表單通知我所需的下拉列表沒有選定的值,但它沒有。我究竟做錯了什麼?

這裏是視圖模型:

public class RequestCreateViewModel 
{ 
    public int ID { get; set; } 

    public TesterLocationCreateViewModel TesterLocationCreateViewModel { get; set; } 

    .... 

    public RequestCreateViewModel() 
    { 

    } 
} 

public class TesterLocationCreateViewModel 
{ 
    public int ID { get; set; } 

    [Required] 
    [UIHint("OEM")] 
    public string OEM { get; set; } 

    [Required] 
    [DisplayName("City")] 
    public string LocationCity { get; set; } 


    public TesterLocationCreateViewModel() 
    { 

    } 
} 

這裏的Create.cshtml

@model WdcTesterManager.Models.Request 

@{ 
    ViewBag.Title = "Create Request"; 
    Layout = "~/Views/Shared/_Layout.cshtml"; 
} 

<h2>Create Request</h2> 

@using (Html.BeginForm()) 
{ 
     @Html.AntiForgeryToken() 
     <div class="form-horizontal"> 
      @Html.ValidationSummary(true, "", new { @class = "text-danger" }) 
      <div class="form-group"> 
       @Html.EditorFor(model => model.TesterLocationCreateViewModel) 
      </div> 
     </div> 
} 

片段這裏的TesterLocationCreateViewModel.cshtml(編輯模板):

@model WdcTesterManager.Models.TesterLocationCreateViewModel 

    <div class="col-md-6"> 
     <h4>Tester Location</h4> 
     <div class="container-fluid"> 
      <div class="form-group"> 
       @Html.LabelFor(model => model.OEM, htmlAttributes: new { @class = "control-label col-md-4" }) 
       <div class="col-md-8"> 
        @Html.DropDownList("OEM", (SelectList)ViewBag.OemList, "Choose one", new { @class = "form-control" }) 
        @Html.ValidationMessageFor(model => model.OEM, "", new { @class = "text-danger" }) 
       </div> 
      </div>    
      <div class="form-group"> 
       @Html.LabelFor(model => model.LocationCity, htmlAttributes: new { @class = "control-label col-md-4" }) 
       <div class="col-md-8"> 
        @Html.EditorFor(model => model.LocationCity, new { htmlAttributes = new { @class = "form-control" } }) 
        @Html.ValidationMessageFor(model => model.LocationCity, "", new { @class = "text-danger" }) 
       </div> 
      </div>    
     </div> 
    </div> 

當我提交表單時沒有填寫任何內容,我得到了城市的驗證錯誤,但沒有提供OEM。有任何想法嗎?

enter image description here

+0

是您查看使用'TesterLocationCreateViewModel':

我改變了Create.cshtml使用RequestCreateViewModel後得到正確的驗證錯誤?在這種情況下,你也需要'[Required]'屬性。 –

+0

是的,它正在使用該視圖模型。我只是添加了[Required],但沒有幫助:/ – AndeeC

+0

嗯 - 某些東西沒有意義,因爲如果您使用的視圖模型沒有[[UIHint]],那麼EditorFor()'永遠不會生成下拉列表。 –

回答

1

@StephenMuecke指出,好像有問題的代碼,因爲代碼似乎引用請求模型,而不是請求視圖模型。

因此,我再次看了一下代碼,發現Create.cshtml使用的是Request模型,而不是RequestCreateViewModel。

@model WdcTesterManager.Models.RequestCreateViewModel