views:

491

answers:

2

Hi, 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

A: 

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.

Kelsey
Thanks Kelsey, I'll check out the article.The SelectedValue parameter was only my last attemp. On the whole I haven't used it.I just set it to try to preselect the value in the edit form.I think it may be an issue in my nhibernate mapping, not setting the child object.I'll look down that route.
Rod McLeay
I get this error when I dont set Lazy loading to false in the nhibernate mapping.Initializing[AgileThought.ERP.Domain.Property.Project#8260fd30-97e7-46f4-818a-689f1e65a91c]-Could not initialize proxy - no Session.
Rod McLeay
And when I try to edit it, I am getting the following Model Validation error.The value 'fd38c877-706f-431d-b624-1269184eeeb5' is invalid.This suggests its trying to push my GUID into the object.Pulling my hair out...
Rod McLeay
I think I'll raise a Nhibernate question.Thanks for you time.
Rod McLeay
A: 

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.

Rod McLeay