MVC Dropdown List isn't binding to the model
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
OMG I found the problem........
It has taken me 3 days to turn:
<%= Html.DropDownListFor(model => model.Aspect, (IEnumerable<SelectListItem>)ViewData["AspectTypes"])%>
into:
<%= Html.DropDownListFor(model => model.Aspect.EntityGUID, (IEnumerable<SelectListItem>)ViewData["AspectTypes"])%>
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.
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 a DropDownList
and had the SelectList
's SelectedValue
set.
Try removing that and see how it goes.
SelectList(projectRepository.GetAll(), "EntityGUID", "Name");
Also I asked a question a while back regarding how to implement DropDownList
in MVC2 that you might find useful.
精彩评论