MVC dropdown is optional for model

I'm trying to set up a simple dropdown but I can't seem to get it to bind to the model. I am using Asp.Net MVC and nhibernate.

My dropdown is declared like this:

<%= Html.DropDownListFor(model => model.Project, (IEnumerable<SelectListItem>)ViewData["Projects"], " -- Select -- ", new { name = "Project" })%>

      

I set up the picklist like this:

ViewData["Projects"] = new SelectList(projectRepository.GetAll(), "EntityGUID", "Name", editEntity.Project);

      

It looks like the picklist is bound to the Dropdown value, but the SelectedValue is not set. it shows as default --- Select ---

Also, when I save this data, the dropdown is not bindable to the model, I have to manually set this object in such a way as to save it:

entity.Project = projectRepository.GetById(new Guid(Request["Project"].ToString()));

      

I believe I took the right mess to link this element directly to my model. Is there something missing here?

Thanks so much for your time Rod

0


a source to share


2 answers


OMG I found the problem ........

It took me 3 days to turn:

<%= Html.DropDownListFor(model => model.Aspect, (IEnumerable<SelectListItem>)ViewData["AspectTypes"])%>

      

at



<%= Html.DropDownListFor(model => model.Aspect.EntityGUID, (IEnumerable<SelectListItem>)ViewData["AspectTypes"])%>

      

model.Aspect **. ** EntityGUID I had to bind the drop to the guid objects rather than the entity itself. Doh .... I feel pain, a lot of work to catch up.

Thank you for your time.

+6


a source


This is just a guess, since your code looks good to me, but I don't think you need to include the fourth parameter when defining SelectList

. Setting this field can interrupt the normal flow of things (overriding the binding of the model) and I never bound DropDownList

and had a set SelectList

SelectedValue

.

Try removing that and see how it goes.



SelectList(projectRepository.GetAll(), "EntityGUID", "Name"); 

      

Also I asked a question about how to implement DropDownList

in MVC2, which may be useful to you.

0


a source







All Articles