asp.net-mvc – ASP.NET MVC – Html.DropDownList – 值未通过ViewData.Model设置

刚刚开始玩ASP.NET MVC,并且偶然发现了以下情况。它感觉很像一个错误,但如果它不,一个解释将不胜感激:)

视图包含相当基本的东西

<%=Html.DropDownList("MyList",ViewData["MyListItems"] as SelectList)%>
<%=Html.TextBox("MyTextBox")%>

当不使用模型时,值和所选项目按预期设置:

//works fine
public ActionResult MyAction(){
  ViewData["MyListItems"] = new SelectList(items,"Value","Text"); //items is an ienumerable of {Value="XXX",Text="YYY"}

  ViewData["MyList"] = "XXX"; //set the selected item to be the one with value 'XXX'
  ViewData["MyTextBox"] = "ABC"; //sets textBox value to 'ABC'

  return View();
}

但是,当尝试通过模型加载时,文本框的值将按预期设置,但下拉列表中没有获取所选项目集。

//doesnt work
public ActionResult MyAction(){
  ViewData["MyListItems"] = new SelectList(items,Text="YYY"}

  var model = new {
    MyList = "XXX",//set the selected item to be the one with value 'XXX'
    MyTextBox = "ABC" //sets textBox value to 'ABC'
  }

  return View(model);
}

有任何想法吗?我目前的想法是,也许在使用模型时,我们仅限于在SelectList构造函数上设置所选项目,而不是使用viewdata(可以正常工作),并将选择列表传递给模型 – 这将有利于清理代码一点点 – 我只是想知道为什么这种方法不工作….

非常感谢任何建议

解决方法

经过一连串的折边和歪斜,它归结为以下代码
if (ViewData.ModelState.TryGetValue(key,out modelState))

这意味着MVC正在尝试通过仅查看ViewData Dictionary<>对象,而不是遍历到ViewData.Model对象。

无论是错误,限制还是设计决定,我都不确定。但是,您可以通过以下方式进行修复:

<%= Html.TextBox("MyTextBox",ViewData.Model.MyTextBox) %>

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....