如何在不使用方法参数的情况下访问ASP.NET MVC中的CheckBox值

时间:2020-11-25 03:26:57

I use the following HTML helper to generate check box:

我使用以下HTML帮助程序生成复选框:

<%= Html.CheckBox("DeluxeFeature")%>

Now I want to access the value of this checkbox in my controller. How should I do this? I am not going to use the method parameter name, for the reason that there are a lot of checkboxes and putting all of them in the parameter will clutter the method.

现在我想在我的控制器中访问此复选框的值。我该怎么做?我不会使用方法参数名称,因为有很多复选框,并且将所有这些复选框放在参数中会使方法混乱。

I try to use

我试着用

Request.Form["DeluxeFeature"]

But the behavior is very weird; if the checkbox is not ticked, then the Request.Form["DeluxeFeature"] returns "false", which is expected. But if the checkbox is ticked, then it retruns "true, false".

但这种行为很奇怪;如果没有勾选复选框,则Request.Form [“DeluxeFeature”]返回“false”,这是预期的。但是如果勾选了复选框,那么它会重新生成“true,false”。

Very weird, isn't it?

很奇怪,不是吗?

2 个解决方案

#1


This thread on the asp.net forums explains the behavior - there's even a comment by Phil Haack from the ASP.NET MVC project team (bonus!!).

asp.net论坛上的这个帖子解释了这个行为 - 甚至还有来自ASP.NET MVC项目团队的Phil Haack的评论(奖金!!)。

So the best way to handle it if you're not using the helpers/model binders as posted by levib seems to be

因此,如果您没有使用levib发布的帮助器/模型绑定器,那么处理它的最佳方法似乎是

Request.Form.GetValues("DeluxeFeature")[0]

#2


This worked for me.

这对我有用。

var checkbox = Request.Form.Get("DeluxeFeature");
if (checkbox.Contains("true"))
{
    //Whatever code if the checkbox is checked.
}

#1


This thread on the asp.net forums explains the behavior - there's even a comment by Phil Haack from the ASP.NET MVC project team (bonus!!).

asp.net论坛上的这个帖子解释了这个行为 - 甚至还有来自ASP.NET MVC项目团队的Phil Haack的评论(奖金!!)。

So the best way to handle it if you're not using the helpers/model binders as posted by levib seems to be

因此,如果您没有使用levib发布的帮助器/模型绑定器,那么处理它的最佳方法似乎是

Request.Form.GetValues("DeluxeFeature")[0]

#2


This worked for me.

这对我有用。

var checkbox = Request.Form.Get("DeluxeFeature");
if (checkbox.Contains("true"))
{
    //Whatever code if the checkbox is checked.
}