How can i check if FormCollection["key"] exists

Niclas Lindqvist picture Niclas Lindqvist · Jun 28, 2011 · Viewed 7.2k times · Source

I'm using ASP.NET MVC 3 and I post a form in my view, containing a @Html.ListBoxFor

When I receive the posted form as a FormCollection, how can I check if an item was selected in the ListBox?

In my controller there seems to be no item named collection["Company.RepresentingCountries"] since no <select> option was selected.. This results in a "Object reference not set to an instance of an object." error message when I try to check for it! What's the protocol here?

Thanks!

Answer

Goran Obradovic picture Goran Obradovic · Jun 28, 2011

You can access form contents in this way:

foreach (var key in Request.Form.AllKeys)
{
    System.Diagnostics.Debug.WriteLine(string.Format("{0}:{1}", key, Request.Form[key]));
}

You can see what you wrote to Debug with tool like DebugView. Of course, you can set a breakpoint here or inspect this collection in any other manner.

<select> always has 'selected' value when posting (if user has not chosen it, then it is the first option that was in it), so if you set "empty" default, it will be posted in collection and its value will be "" (string.Empty).

UPDATE When select has multiple="multiple" attribute, then none selected value means that form serialization will not take it into account, so it wont be part of form collection. To check if you have selected value, use collection["Company.RepresentingCountries"] == null, or String.IsNullOrEmpty(collection["Company.RepresentingCountries"]). Both will be true when there is no selected value, although second one might be true in case you have empty option in select.