我如何检查 FormCollection[“key”] 是否存在
我正在使用 ASP.NET MVC 3,并在视图中发布一个表单,其中包含 @Html.ListBoxFor
当我收到以 FormCollection 形式发布的表单时,如何检查是否选择了某个项目在列表框中?
在我的控制器中,似乎没有名为 collection["Company.RepresentingCountries"]
的项目,因为没有选择
谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以通过以下方式访问表单内容:
您可以使用 DebugView 等工具查看您向 Debug 写入的内容。
当然,您可以在此处设置断点或以任何其他方式检查此集合。
<选择>发布时始终具有“选定”值(如果用户未选择它,则它是其中的第一个选项),因此如果您设置“空”默认值,它将发布在集合中,其值将为“” (字符串。空)。
UPDATE 当 select 有 multiple="multiple" 属性时,没有选择值意味着表单序列化不会考虑它,因此它不会成为表单集合的一部分。要检查您是否已选择值,请使用
collection["Company.RepresentingCountries"] == null
或String.IsNullOrEmpty(collection["Company.RepresentingCountries"])
。当没有选定值时,两者都为 true,但如果 select 中有空选项,则第二个可能为 true。You can access form contents in this way:
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
, orString.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.您还没有显示您的
ListBoxFor
帮助器是如何定义的,所以我只能在这里猜测。话虽如此,您谈到了我不推荐使用的FormCollection
。我推荐的是使用视图模型。让我们举个例子:模型:
控制器:
视图:
You haven't shown how your
ListBoxFor
helper is defined, so I can only be guessing here. This being said you talked aboutFormCollection
which usage I wouldn't recommend. What I recommend is using view models. So let's take an example:Model:
Controller:
View: