将 DropDownList 填充到 ASCX 控件中
我想将下拉列表填充到 ASCX 中。 为此,我在控制器中使用 LINQ 查询并将结果填充到 viewModel 中。 从视图生成下拉列表可以,但从 ASCX 不行! 您知道为什么这行不通吗?
提前致谢:-)
控制器中的代码
var query = from foo in session.Linq<PROJECT.Models.bar>() select foo;
PROJECT.ViewModels.myviewmodel viewModel = new PROJECT.ViewModels.myviewmodel();
viewModel.data = new SelectList(query, "Id", "title");
return View(viewModel);
视图中的代码
<h2>Create</h2>
<%= Html.EditorFor(a => a.evaluation, new { EvaluationTypes = Model.evaluationTypes })%>
<!-- Generate from here is ok -->
<%: Html.DropDownList("foo",Model.evaluationTypes) %>
ASCX 中的代码
<%= ViewData["EvaluationTypes"] %>
<%: Html.DropDownList("foo", ViewData["EvaluationTypes"])%>
I want to fill a dropdownlist into an ASCX.
To do that, in the controler i use a LINQ query and fill the result into a viewModel.
Generate the dropdown is ok from the view but not from the ASCX !
Have you an idea of why this don't work ?
Thank's by advance :-)
Code in controler
var query = from foo in session.Linq<PROJECT.Models.bar>() select foo;
PROJECT.ViewModels.myviewmodel viewModel = new PROJECT.ViewModels.myviewmodel();
viewModel.data = new SelectList(query, "Id", "title");
return View(viewModel);
Code in view
<h2>Create</h2>
<%= Html.EditorFor(a => a.evaluation, new { EvaluationTypes = Model.evaluationTypes })%>
<!-- Generate from here is ok -->
<%: Html.DropDownList("foo",Model.evaluationTypes) %>
Code in ASCX
<%= ViewData["EvaluationTypes"] %>
<%: Html.DropDownList("foo", ViewData["EvaluationTypes"])%>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我建议您使用强类型编辑器模板并放弃 ViewData:
并在 EditorTemplate 中:
更新:
在发布异常堆栈跟踪后,我发现了问题:
您需要转换为
SelectList
您的ViewData["EvaluationTypes"]
。话虽这么说,应该通过使用强类型助手来避免那些丑陋的强制转换,正如我在最初的答案中所建议的那样。I would suggest you using a strongly typed Editor Template and abandon ViewData:
and in the EditorTemplate:
UPDATE:
After you've posted your exception stack trace I've spotted the problem:
You need to cast to
SelectList
yourViewData["EvaluationTypes"]
. This being said those ugly casts should be avoided by using strongly typed helpers as I suggested in my initial answer.