Asp.Net MVC 5 Html.DropDownList 未验证

Asp.Net MVC 5 Html.DropDownList is not validating

我已经被这个问题困扰了一段时间,似乎无法在网上找到任何有帮助的东西。

我在编辑器模板中有一个 Html.DropDownList。我在我的表单中使用该模板,并且不 select 任何下拉列表。当我单击提交时,我希望表单通知我所需的下拉列表没有值 selected,但它没有。我究竟做错了什么?

以下是视图模型:

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 没有任何验证错误。有什么想法吗?

@StephenMuecke 指出代码看起来有问题,因为代码似乎引用了请求模型而不是请求视图模型。

因此,我再次查看代码并意识到 Create.cshtml 使用的是 Request 模型而不是 RequestCreateViewModel。

将 Create.cshtml 更改为使用 RequestCreateViewModel 后,我收到了正确的验证错误:

@model WdcTesterManager.Models.RequestCreateViewModel