MVC 下拉列表未绑定到模型
我正在尝试设置一个简单的下拉列表,但我似乎无法将其绑定到模型。 我正在使用 Asp.Net MVC 和 nhibernate。
我的下拉列表声明如下:
<%= Html.DropDownListFor(model => model.Project, (IEnumerable<SelectListItem>)ViewData["Projects"], " -- Select -- ", new { name = "Project" })%>
我像这样设置选择列表:
ViewData["Projects"] = new SelectList(projectRepository.GetAll(), "EntityGUID", "Name", editEntity.Project);
这似乎将选择列表绑定到下拉列表,但未设置 SelectedValue。 它显示为默认值 --- 选择 ---
另外,当我保存此数据时,下拉列表不会绑定到模型,我必须像这样手动设置对象才能保存它:
entity.Project = projectRepository.GetById(new Guid(Request["Project"].ToString()));
我相信我已经采取了正确的措施将此项目直接绑定到我的模型。 我在这里缺少什么吗?
非常感谢您抽出时间, 杆
I am trying set up a simple dropdown list but I dont seem to be able to get it to bind to the Model.
I am using Asp.Net MVC and nhibernate.
My dropdown list is declared like so:
<%= Html.DropDownListFor(model => model.Project, (IEnumerable<SelectListItem>)ViewData["Projects"], " -- Select -- ", new { name = "Project" })%>
I set up the select list like so:
ViewData["Projects"] = new SelectList(projectRepository.GetAll(), "EntityGUID", "Name", editEntity.Project);
This seems to bind the select list to the Dropdown fine, but the SelectedValue is not set.
it shows up as the default --- Select ---
Also when I save this data, the dropdown does not bind to the model, I have to manually set the object like so to save it:
entity.Project = projectRepository.GetById(new Guid(Request["Project"].ToString()));
I believe I have take the correct messures to have this item bind directly to my model.
Is there something I am missing here?
Many thanks for your time,
Rod
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
天哪,我发现了问题........
我花了3天时间才把:
变成:
model.Aspect**.EntityGUID**
我必须将下拉菜单绑定到对象 guid,而不是对象本身。
Doh....我感到痛苦,还有很多工作要做。
感谢您抽出时间。
OMG I found the problem........
It has taken me 3 days to turn:
into:
model.Aspect**.EntityGUID**
I had to bind the drop down to the objects guid, not the object itself.
Doh....Im feeling the pain, much work to catch up on.
Thanks for your time.
这只是一种预感,因为您的代码对我来说看起来不错,但我认为您在定义
SelectList
时不需要包含第四个参数。设置该字段可能会扰乱事物的正常流程(覆盖您的模型绑定),并且我从未绑定过 DropDownList 并拥有 SelectList 的 SelectedValue代码>设置。尝试删除它,看看效果如何。
另外我不久前问了一个问题有关如何在 MVC2 中实现 DropDownList 的信息,您可能会觉得有用。
This is just a hunch since your code looks good to me but I don't think you need to include the forth parameter when defining your
SelectList
. Setting that field might be distrupting the normal flow of things (overriding your model binding) and I have never bound aDropDownList
and had theSelectList
'sSelectedValue
set.Try removing that and see how it goes.
Also I asked a question a while back regarding how to implement
DropDownList
in MVC2 that you might find useful.