我如何检查 FormCollection[“key”] 是否存在

发布于 2024-11-17 06:13:07 字数 314 浏览 8 评论 0原文

我正在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

站稳脚跟 2024-11-24 06:13:07

您可以通过以下方式访问表单内容:

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

您可以使用 DebugView 等工具查看您向 Debug 写入的内容。
当然,您可以在此处设置断点或以任何其他方式检查此集合。

<选择>发布时始终具有“选定”值(如果用户未选择它,则它是其中的第一个选项),因此如果您设置“空”默认值,它将发布在集合中,其值将为“” (字符串。空)。

UPDATE 当 select 有 multiple="multiple" 属性时,没有选择值意味着表单序列化不会考虑它,因此它不会成为表单集合的一部分。要检查您是否已选择值,请使用collection["Company.RepresentingCountries"] == nullString.IsNullOrEmpty(collection["Company.RepresentingCountries"])。当没有选定值时,两者都为 true,但如果 select 中有空选项,则第二个可能为 true。

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.

乖乖公主 2024-11-24 06:13:07

您还没有显示您的 ListBoxFor 帮助器是如何定义的,所以我只能在这里猜测。话虽如此,您谈到了我不推荐使用的 FormCollection 。我推荐的是使用视图模型。让我们举个例子:

模型:

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" },
            };
        }
    }
}

控制器:

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);
    }
}

视图:

@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" />
}

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" />
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文