使用 Html.DropDownListFor 时 ModelsState 始终无效
这就是我创建下拉列表的方式
@Html.DropDownListFor(model => model.NewPageModel.AvailablePageModels, new SelectList(Model.NewPageModel.AvailablePageModels, "Text", "Value"))
,这就是我的可用页面模型的样子
public IEnumerable<SelectListItem> AvailablePageModels
{
get
{
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
foreach (var type in assembly.GetTypes())
{
if (type.GetCustomAttributes(typeof(PageModelAttribute), true).Length > 0)
{
yield return new SelectListItem { Text = type.Name, Value = type.Name };
}
}
}
}
}
,当我将表单发布到以下操作时,我的模型状态始终无效并且错误发生在可用页面模型值上?也许我不能以这种方式使用 NewPageModel 作为参数?
public ActionResult Create([Bind(Prefix = "NewPageModel")] NewPageModel newPageModel, FormCollection collection)
{
if(ModelState.IsValid) {
// always invalid
}
}
This is how I create my dropdown
@Html.DropDownListFor(model => model.NewPageModel.AvailablePageModels, new SelectList(Model.NewPageModel.AvailablePageModels, "Text", "Value"))
and this is how my AvailablePageModels looks like
public IEnumerable<SelectListItem> AvailablePageModels
{
get
{
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
foreach (var type in assembly.GetTypes())
{
if (type.GetCustomAttributes(typeof(PageModelAttribute), true).Length > 0)
{
yield return new SelectListItem { Text = type.Name, Value = type.Name };
}
}
}
}
}
and when I post my form to the following action my modelstate is always invalid and the error occur on the AvailablePageModel value? Maybe I cannot use the NewPageModel as a parameter this way?
public ActionResult Create([Bind(Prefix = "NewPageModel")] NewPageModel newPageModel, FormCollection collection)
{
if(ModelState.IsValid) {
// always invalid
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要 2 个字段,一个用于下拉列表中的可用选项,另一个用于存储所选值
You need 2 fields, one for the available options in the drop down list and one for storing the selected value