将 DropDownListFor 与 ValidationMessageFor 结合使用

Using DropDownListFor in combination with ValidationMessageFor

我目前正在尝试组合 Html 辅助函数 DropDownListForValidationMessageFor。我正在使用 asp.Net MVC 5 并生成了一个模型。我的目标是有一个 HTML select-box,它是由函数 DropDownListFor 生成的。这应该链接到我的模型。假定客户端在 select-box 的前端字段中输入了一些内容。如果客户端没有输入任何内容并单击我的表单的提交按钮,则应该使用 ValidationMessageFor 函数来显示我在模型中输入的错误文本。当然,只要 select-box 中没有 selected,表单就不应有效,并且不应允许客户端继续。这就是理论。

如前所述,我已经创建了一个模型。它看起来像这样:

public class ExampleModel
{        
    [Required(ErrorMessage="Test-Error-Text")]
    public string salutation { get; set; }
}

我在控制器的 select 框中设置值如下:

var collection = new ListItemCollection();
collection.Add(new ListItem("Mr"));
collection.Add(new ListItem("Mrs"));
collection.Add(new ListItem("unknown"));
collection.Add(new ListItem("company"));

var selList = new SelectList(collection, "Salutation");
ViewBag.Salutation = selList;

然后我调用视图中的函数如下:

@Html.DropDownListFor(Model=> Model.salutation, ViewBag.Salutation as SelectList, "", new { @class="adrInput form-control"})            
@Html.ValidationMessageFor(Model=>Model.salutation)

由于目前的情况,我在提交时遇到以下异常:

System.InvalidOperationException: 'There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'salutation'.'

我几乎从未使用过这些 Html 辅助函数。这里不对劲。我很感激任何帮助。

在你的VIEW中,你会碰巧有这样的东西吗?

@model IEnumerable<Sample1.Models.ExampleModel>

如果是,删除 "IEnumerable",然后执行:

@model Sample1.Models.ExampleModel

我发现了错误。如果表单无效,我必须在提交表单后 return 将模型添加到视图中。此外,我必须再次为 ViewBag 初始化 SelectList。不知何故,验证后 ViewBag.Salutation 中的值丢失了。