我一直坚持这个问题一段时间,似乎无法在网上找到任何有用的东西。
我在编辑器模板中有一个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。有什么想法吗?
答案 0 :(得分:1)
@StephenMuecke指出代码出现了问题,因为代码似乎引用了Request模型而不是Request View模型。
所以,我再看了一下代码,发现Create.cshtml使用的是Request模型而不是RequestCreateViewModel。
在更改Create.cshtml以使用RequestCreateViewModel后,我收到了正确的验证错误:
@model WdcTesterManager.Models.RequestCreateViewModel