在尝试使用必填字段验证创建下拉控件时,我曾经收到此消息:
具有键'SelectedNCRType'的ViewData项的类型为'System.Int32' 但必须是“IEnumerable”类型。
不知怎的,我设法让一切都在我的本地机器上工作,一切都很好看。然而,当我发布项目并将文件复制到测试服务器时,只要下拉控件上的验证失败,就会再次显示此消息。以下是一些代码段:
View Model:
[DisplayName("NCR Type:")]
public IEnumerable<SelectListItem> NCRTypeSelectList
{
get;
set;
}
[Range(1, Int32.MaxValue, ErrorMessage = "Required Field")]
public int SelectedNCRType { get; set; }
Controller:
var types = (from x in context.NCRTypes
where x.Deleted == false
select new models.NCRType
{
Deleted = x.Deleted,
Id = x.Id,
Name = x.Name
}).ToList();
model.NCRTypeSelectList = types.ToSelectList("Id", "Name");
View:
<%= Html.DropDownListFor(x => x.SelectedNCRType, Model.NCRTypeSelectList, "Select...", new { @class = "form_dropdown_300" })%>
<%= Html.ValidationMessageFor(model => model.SelectedNCRType, "Required Field")%>
Helper Extension Method:
public static SelectList ToSelectList<T>(this IEnumerable<T> collection,
string dataValueField, string dataTextField)
{
return new SelectList(collection, dataValueField, dataTextField);
}
如果您有任何想法,请帮助......这让我发疯。
答案 0 :(得分:0)
我通过在行之前重新填充post action方法中的下拉控件来实现这一点:
返回视图(模型);