【发布时间】:2016-04-23 03:23:57
【问题描述】:
我已经被这个问题困扰了一段时间,似乎无法在网上找到任何有帮助的东西。
我在编辑器模板中有一个 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 的 sn-p
@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>
当我在未填写任何内容的情况下提交表单时,我收到了 City 的验证错误,但 OEM 却没有。有什么想法吗?
【问题讨论】:
-
您是否使用
TesterLocationCreateViewModel查看?在这种情况下,您还需要[Required]属性。 -
是的,它正在使用该视图模型。我刚刚添加了 [Required] 但它没有帮助:/
-
嗯 - 有些事情没有意义,因为如果您使用没有
[UIHint]的视图模型,那么EditorFor()将永远不会生成下拉列表。 -
[UIHint]是在数据模型中设置的,似乎不必在视图模型中设置,因为它无需我在视图模型中设置即可工作。我也对此感到困惑...... -
这是不可能的。并且您收到
LocationCity的错误消息,这也是不可能的,因为视图模型中的属性未标记为[Required]。您显示的代码有问题。
标签: c# asp.net-mvc drop-down-menu mvc-editor-templates html-validation