C# 将DropDownListFor与ValidationMessageFor结合使用

C# 将DropDownListFor与ValidationMessageFor结合使用,c#,asp.net-mvc,html-helper,C#,Asp.net Mvc,Html Helper,我目前正在尝试将Html助手函数DropDownListFor和ValidationMessageFor组合起来。我使用asp.NETMVC5并生成了一个模型。我的目标是拥有一个HTML选择框,它由函数DropDownListFor生成。这应该链接到我的模型。假设客户端在选择框前端的字段中输入了一些内容。如果客户端没有输入任何内容并单击我表单的提交按钮,则应使用ValidationMessageFor函数显示我在模型中输入的错误文本。当然,表单不应该是有效的,只要在选择框中没有选择任何内容,就不

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

如前所述,我创建了一个模型。看起来是这样的:

public class ExampleModel
{        
    [Required(ErrorMessage="Test-Error-Text")]
    public string salutation { get; set; }
}
我在控制器的选择框中设置值,如下所示:

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)
然后我调用视图中的函数,如下所示:

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'.'
System.InvalidOperationException:“没有类型为“IEnumerable”且键为“Sallation”的ViewData项。”

我几乎从未使用过这些Html助手函数。这里有点不对劲。非常感谢您的帮助。

在您看来,您会有这样的东西吗

@model IEnumerable<Sample1.Models.ExampleModel>

我发现了错误。如果表单无效,我必须在提交表单后将模型返回视图。此外,我必须再次初始化ViewBag的SelectList。不知怎的,这些值在ViewBag中丢失了。验证后问候。

否。在我看来,我将模型集成如下:
@model Samlple1.Models.ExampleModel