将 DropDownList 填充到 ASCX 控件中

发布于 2024-10-04 02:06:13 字数 885 浏览 2 评论 0原文

我想将下拉列表填充到 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

满意归宿 2024-10-11 02:06:13

我建议您使用强类型编辑器模板并放弃 ViewData:

<%: Html.EditorFor(x => x.evaluation) %>

并在 EditorTemplate 中:

<%: Html.DropDownListFor(x => x.foo, Model.evaluationTypes) %>

更新:

在发布异常堆栈跟踪后,我发现了问题:

<%: Html.DropDownList("foo", (SelectList)ViewData["EvaluationTypes"])%>

您需要转换为 SelectList您的ViewData["EvaluationTypes"]。话虽这么说,应该通过使用强类型助手来避免那些丑陋的强制转换,正如我在最初的答案中所建议的那样。

I would suggest you using a strongly typed Editor Template and abandon ViewData:

<%: Html.EditorFor(x => x.evaluation) %>

and in the EditorTemplate:

<%: Html.DropDownListFor(x => x.foo, Model.evaluationTypes) %>

UPDATE:

After you've posted your exception stack trace I've spotted the problem:

<%: Html.DropDownList("foo", (SelectList)ViewData["EvaluationTypes"])%>

You need to cast to SelectList your ViewData["EvaluationTypes"]. This being said those ugly casts should be avoided by using strongly typed helpers as I suggested in my initial answer.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文