How can i check if FormCollection["key"] exists
I'm using ASP.NET MVC 3 and I post a form in my view, containing开发者_StackOverflow社区 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!
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.
You haven't shown how your ListBoxFor
helper is defined, so I can only be guessing here. This being said you talked about FormCollection
which usage I wouldn't recommend. What I recommend is using view models. So let's take an example:
Model:
public class MyViewModel
{
[Required(ErrorMessage = "Please select at least one item")]
public string[] SelectedItemIds { get; set; }
public SelectListItem[] Items
{
get
{
return new[]
{
new SelectListItem { Value = "1", Text = "Item 1" },
new SelectListItem { Value = "2", Text = "Item 2" },
new SelectListItem { Value = "3", Text = "Item 3" },
};
}
}
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
SelectedItemIds = new[] { "1", "3" }
};
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
if (ModelState.IsValid)
{
// The model is valid we know that the user selected
// at least one item => model.SelectedItemIds won't be null
// Do some processing ...
}
return View(model);
}
}
View:
@model MyViewModel
@using (Html.BeginForm())
{
@Html.ListBoxFor(
x => x.SelectedItemIds,
new SelectList(Model.Items, "Value", "Text")
)
@Html.ValidationMessageFor(x => x.SelectedItemIds)
<input type="submit" value="OK" />
}
精彩评论