Asp.Net MVC 5 Html.DropDownList未验证

问题描述:

我一直在这个问题上停留了一段时间,似乎无法找到任何有助于解决的问题。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()'永远不会生成下拉列表。 –

@StephenMuecke指出,好像有问题的代码,因为代码似乎引用请求模型,而不是请求视图模型。

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

@model WdcTesterManager.Models.RequestCreateViewModel