views:

482

answers:

2

We're using ASP.NET MVC together with NHibernate and we'd like to create several Dropdown Lists using Values (custom Class) from the Database. This actually works, but how do I handle the "Empty" value; I mean, the "unselected" DropdownValue? Something like "-- Select --" on the top of the List... Does anyone have experience with this combination NHibernate, ASP.NET MVC and Dropdown?

Thanks!

+1  A: 

I think this is easily handled by using a ViewModel class. Lets say you have an OrderView in your app, which displays an order. On this view you have a dropdown "Item Type", containing a list of item types.

The model that should be fed to your view should be a class like OrderViewModel which contains a list of ItemType objects. When the controller loads the list of ItemType objects from the DB using NHib, it can then insert extra "special" Item Types into the collection, such as one for "--SELECT--".

In other words, don't bind directly to an Nhibernate collection mapping property -- use Nhibernate to load data into a list which you can then manipulate at will.

HokieMike
hi HokieMike, thanks a lot for your first suggestion! I am using the ViewModel Pattern already. (by the way, it gets trickier if Master/Details Views join the game)This is how i'm doing it at the moment: On the View I call the Method "AsSelectList" on the custom class property which returns me the SelectList of that dropdown type. Inside this Method, the "--Select--" gets added from database with the IdValue 1. This is working without problems. But if it comes to saving the object, i'd prefer to have "NULL" in the DB if "--Select--" was selected and not the foreign key 1 of "--Select--"...
stromflut
A: 

Best way to have a "--select--" value in Dropdown will be the parameter optionLabel which is available in Html.DropdownList

Then save "null" to your database and you should have a clean way ;)

<%= Html.DropDownList("myDropdown",mylist,"--please choose--" %>
griti