【发布时间】:2015-10-11 13:35:09
【问题描述】:
我正在使用 Visual Studio 2015 社区版进行 ASP.net MVC 项目测试, 这是我的简单模型:
public class TestModel
{
[Required]
public string Name { get; set; }
[UIHint("EnumList")]
public TestState State { get; set; }
}
public enum TestState
{
eNone,
eNew,
eFinished,
}
这是一个通用的 html - EnumList.cshtml
@model Enum
@Html.DropDownListFor(m => m, Enum.GetValues(Model.GetType()).OfType<Enum>()
.Select(m =>
{
string enumVal = Enum.GetName(Model.GetType(), m);
return new SelectListItem()
{
Selected = (Model.ToString() == enumVal),
Text = enumVal,
Value = enumVal
};
})
)
如果在接受 TestModel 作为模型的测试视图中使用下面的内容,它可以正常工作。
@Html.EditorForModel()
但是,当我尝试通过以下特定操作使用上面的 EnumList.cshtml 时:
@Html.Action("Enum", new { pState = Model.State }); <-- used in View html
// below action will be called by above method
[ChildActionOnly]
public PartialViewResult Enum(TestState? pState)
{
return PartialView("~/Views/Shared/EditorTemplates/EnumList.cshtml", pState.HasValue ? pState.Value : TestState.eNone);
}
我收到以下错误:
值不能为 null 或空。 参数名称:名称
以下来自堆栈跟踪:
[ArgumentException:值不能为空或空。
参数名称:名称]
System.Web.Mvc.Html.SelectExtensions.SelectInternal(HtmlHelper htmlHelper,ModelMetadata 元数据,字符串 optionLabel,字符串名称,IEnumerable1 selectList, Boolean allowMultiple, IDictionary2 htmlAttributes)+589
System.Web.Mvc.Html.SelectExtensions.DropDownListFor(HtmlHelper1 htmlHelper, Expression1 表达式,IEnumerable1 selectList, String optionLabel, IDictionary2 htmlAttributes) +95
System.Web.Mvc.Html.SelectExtensions.DropDownListFor(HtmlHelper1 htmlHelper, Expression1 表达式,IEnumerable`1 selectList) +60
c:\visual studio 2015\Projects\Test\Test1\Views\Shared\EditorTemplates\EnumList.cshtml:3 中的 ASP._Page_Views_Shared_EditorTemplates_EnumList_cshtml.Execute()
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +197
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +105
如果在测试视图中直接调用上面的 DropDownListFor() 并进行“m => m.State”之类的更改,它会起作用,所以我相信这个错误与“m => m”有关,但是正确的表达式是什么?
提前致谢。
【问题讨论】:
-
用
@Html.EditorFor(m=>m.State,"EnumList")代替@Html.Action("Enum", new { pState = Model.State }); -
关于 SO 上的 DropDownLists 的问题太多了。
标签: c# asp.net-mvc