Reputation: 1062
I have a problem with mvc DropDownList, lots of topics about that, but not one with the same problem.
I want a default selected option for my DropDownList, but i also need additional option for "all" items selection.
So my controller is binding default value of 2 to dropdown
public ActionResult Index(int? All = 2){ ...
In cshtml i have
@Html.DropDownList("All","All items")
All list is filled like this
ViewData["All"] = new SelectList(CommonLists.property_types.Select(x => new { v = x.Value, t = x.Key.ToLower() }), "v", "t", All);
property_types
public static Dictionary<string, int> property_types = new Dictionary<string, int>() {
{ "House", 1 }, { "Flat", 2 }, { "Garden", 3 }
So it should work like this
I have assumed it should work, but to my surprise, when i select "All items" mvc does not return null it just returns the default int value 2, so basically no way to query for all items.
Is this suppose to work like that? The auto generated "All items" is empty value so i assumed mvc would translate it to null, but it is not.
How to fix this?
Upvotes: 3
Views: 6288
Reputation: 2687
The problem isn't that null
isn't returned by the POST, but that null
IS returned by the POST.
Since your action has a default value of 2. When the action is receiving null
the it's initializing the variable with the default value, in that case 2
public ActionResult Index(int? All = 2)
What you want to do it to be able to differentiate between "All items" and the default behavior of the app. It that case, the default behavior is to show only flats
You can achieve that goal by using building the "All items" inside of your controller.
public ActionResult Index(int? All = 2)
{
var propertyTypesSelectList = new SelectList(property_types.Select(x => new {v = x.Value, t = x.Key.ToLower()}), "v", "t", All).ToList();
propertyTypesSelectList.Insert(0, new SelectListItem() { Value = "0", Text = "All items"});
ViewData["All"] = propertyTypesSelectList;
return View();
}
And changing your View to this
@Html.DropDownList("All")
Upvotes: 4