gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 13:54:43 25 4
gpt4 key购买 nike

刚刚开始使用 ASP.NET MVC 并偶然发现了以下情况。感觉很像一个错误,但如果不是,我们将不胜感激:)

View 包含非常基本的东西

<%=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, "Value", "Text"); //items is an ienumerable of {Value="XXX", 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 构造函数上设置所选项目,而不是使用 View 数据(工作正常)并将选择列表与模型一起传递——这将有好处稍微清理一下代码 - 我只是想知道为什么这种方法不起作用....

非常感谢您的任何建议

最佳答案

实际上,您只需传入 null 对于Html.DropDownList() .
我遇到了同样的问题,并使用反射器查看了 MVC 源代码。

System.Web.Mvc.Extensions.SelectExtensions类(class) SelectInternal()方法,它检查 选择列表 参数为 或不。
如果以 null 的形式传入,它会查找 SelectList适本地。

这是“代码隐藏”。

ViewData["MyDropDown"] = new SelectList(selectListItems,
"Value",
"Text",
selectedValue.ToString()
);

这是 HTML View 代码。
<%= Html.DropDownList("MyDropDown", null,
"** Please Select **",
new { @class = "my-select-css-class" }
) %>

注意:我使用的是 ASP.NET MVC 2.0(测试版)。

更新说明:2012 年 1 月 31 日

在过去 3 年广泛使用 ASP.NET MVC 之后,我更喜欢使用 additionalViewData 来自 Html.EditorFor() method更多的。

传递您的 [列表项] 作为 anonymous带有 的对象相同的属性名称 作为模型的属性到 Html.EditorFor()方法。
<%= Html.EditorFor(
m => m.MyPropertyName,
new { MyPropertyName = Model.ListItemsForMyPropertyName }
) %>

如果您想了解更多详情,请引用 my answer in another thread here .

关于asp.net-mvc - ASP.NET MVC - Html.DropDownList - 值未通过 ViewData.Model 设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/390083/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com