1

I have an MVC app via SharpArch. In the view I have:

 Html.DropDownListFor(x => x.Location, 
     new SelectList(Model.PossibleLocations, "Id", "Address"), 
     "-- No Location --")

I have 2 issues.

  1. The Dropdown is not getting updated when the view gets bound to the model.
  2. A selection gets persisted correctly except when I try the top "no location".

I was able to take care of the first point by changing x.Location to x.Location.Id but then I had other issues.

I can find plenty of examples for DropDownList, but none in which saving a null is shown.

Any help is appreciated.

Thanks

UPDATE:

I just upgraded Resharper (a minor update) and am getting prompted to fill it DropDownListFor. Why would that make a difference? It was working enough to bind and now it doesn't work at all.

Adam Dymitruk
  • 124,556
  • 26
  • 146
  • 141

2 Answers2

1

Try "flattening" your model class so that LocationId is the actual value you're binding to (i.e. add a "LocationId" property to your model, and create a DropDownList for x => x.LocationId).

StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315
  • That doesn't sound good. The model is `WorkOrder *---0|1 Location`. I shouldn't have to explicitly deal with the ids, no? Plus, I can't find any docs on persisting the top item in the dropdown as null. – Adam Dymitruk May 13 '11 at 00:47
  • @adymitruk: So each work-order may have one or no locations, and each location can have any number of work-orders, right? Typically this is modeled using a (nullable) scalar foreign key value (WorkOrder.LocationId). Think of it this way: You're not changing the ID value of the location: you're changing which location the WorkOrder references. So make LocationId a nullable int. If you then add a PossibleLocation with Value = "", similar to hunter's response, you should be able to have it recognize a null value when that item is selected. – StriplingWarrior May 13 '11 at 02:39
1

You could always insert the "empty" SelectListItem into your PossibleLocations collection before passing to the View and check for that "empty" value (0 for instance) when the form is posted

model.PossibleLocations.Insert(0, 
    new SelectListItem() { Text = "-- No Location --", Value = "0" };
hunter
  • 62,308
  • 19
  • 113
  • 113
  • close enough. I ended up adding a null object to the original collection of locations and put in some code in the controller to set the property to null if the null object was being specified. – Adam Dymitruk May 13 '11 at 11:01