C# 将复选框的值传递给 asp.net mvc4 中的控制器操作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18862712/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:26:55  来源:igfitidea点击:

Pass values of checkBox to controller action in asp.net mvc4

c#asp.netasp.net-mvcasp.net-mvc-4checkbox

提问by Nancy

I want to test if the checkbox is checked or not from my action method, what i need is to pass checkbox value from view to controller.

我想测试是否从我的操作方法中选中了复选框,我需要的是将复选框值从视图传递到控制器。

This is my view:

这是我的观点:

   @using (Html.BeginForm("Index", "Graphe"))
    {

           <table style="width: 100%;" border="1">
          <tbody>
          <tr>
          <td>Responsable:</td>
          <td><select id="Responsables" name="responsables"  ><option>Selectionnez --</option></select></td>
           <td><input id="responsable" name="checkResp" type="checkbox" /> </td>
</tr>
               <tr> <td><input type="submit" value="Afficher" id="ButtonSubmit"/></td>

                <td><input class="button" id="ButtonReset" type="button" value="Annuler"  /></td>
            </tr>
</tbody>

and i try that :

我尝试这样做:

 public ActionResult Index(string responsables, bool checkResp)
    {
        Highcharts chart = new Highcharts("chart");

        if (responsables != null)
        {

                if (checkResp)
                chart = Global();

                else
                 chart = Resp(responsables);

            }
        else
            chart = Global();
        return View(chart);

    }

But i receive this Error:

但我收到此错误:

Le dictionnaire de paramètres contient une entrée Null pour le paramètre ? checkAct ? de type non Nullable ? System.Boolean ? pour la méthode ? System.Web.Mvc.ActionResult Index(System.String, System.String, Boolean) ? dans ? Project.Controllers.GrapheController ?. Un paramètre facultatif doit être un type référence, un type Nullable ou être déclaré en tant que paramètre facultatif. Nom du paramètre : parameters

Le dictionnaire de paramètres contient une entrée Null pour le paramètre ? 检查法?de 类型不可空?System.Boolean ? 倒出方法?System.Web.Mvc.ActionResult Index(System.String, System.String, Boolean) ? 丹斯?Project.Controllers.GrapheController ?. Un paramètre facultatif doit être un type référence, un type Nullable ou être déclaré en tant que paramètre facultatif。Nom du paramètre : 参数

Can you help me please !

你能帮我吗 !

采纳答案by Andrew Shepherd

If a checkbox is checked, then the postback values will contain a key-value pair of the form [InputName]=[InputValue]

如果选中了复选框,则回发值将包含以下形式的键值对 [InputName]=[InputValue]

If a checkbox is not checked, then the posted form contains no reference to the checkbox at all.

如果未选中复选框,则发布的表单根本不包含对该复选框的引用。

Knowing this, the following will work:

知道这一点,以下将起作用:

In the markup code:

在标记代码中:

 <input id="responsable" name="checkResp" value="true" type="checkbox" />

And your action method signature:

以及您的操作方法签名:

public ActionResult Index( string responsables, bool checkResp = false)

This will work because when the checkbox is checked, the postback will contain checkResp=true, and if the checkbox is not checked the parameter will default to false.

这将工作,因为检查复选框时,回发将包含checkResp=true,如果未选中该复选框,则参数将默认为false。

回答by Simon Whitehead

You should be strongly typing your views. Then you can do this:

你应该强烈地输入你的观点。然后你可以这样做:

public class YourViewModel {
    public bool ConditionaValue { get; set; }
}

In your view, you can create a checkbox that will bind to this boolean value:

在您的视图中,您可以创建一个复选框来绑定到这个布尔值:

@Html.CheckBoxFor(x => x.ConditionalValue)

If it is checked, the model property will be true.

如果选中,则模型属性将为真。

For your immediate problem though.. you need to name your checkbox to be the same name as your action method parameters.. and they should be bool..

但是,对于您的直接问题.. 您需要将复选框命名为与您的操作方法参数相同的名称.. 它们应该是bool..

回答by COLD TOLD

try using form collection

尝试使用表单集合

<input id="responsable" value="True" name="checkResp" type="checkbox" /> 

[HttpPost]
public ActionResult Index(FormCollection collection)
{
     if(!string.IsNullOrEmpty(collection["checkResp"])
     {
        string checkResp=collection["checkResp"];
        bool checkRespB=Convert.ToBoolean(checkResp);
     }

}

回答by Philip Pittle

For some reason Andrew method of creating the checkbox by hand didn't work for me using Mvc 5. Instead I used this

出于某种原因,Andrew 使用 Mvc 5 手动创建复选框的方法对我不起作用。相反,我使用了这个

@Html.CheckBox("checkResp")

to create a checkbox that would play nice with the controller.

创建一个复选框,可以很好地与控制器配合使用。

回答by Matas Vaitkevicius

If you want your value to be read by MVT controller when you submit the form and you don't what to deal with hidden inputs. What you can do is add valueattribute to your checkboxand set it to trueor false.

如果您希望在提交表单时由 MVT 控制器读取您的值,并且您不知道如何处理隐藏的输入。您可以做的是将value属性添加到您的checkbox并将其设置为truefalse

MVT will not recognize viewModel property myCheckboxas true here

MVT 不会myCheckbox在此处将 viewModel 属性识别为 true

<input type="checkbox" name="myCheckbox" checked="checked" />

<input type="checkbox" name="myCheckbox" checked="checked" />

but will if you add

但如果你添加

<input type="checkbox" name="myCheckbox" checked="checked" value="true" />

<input type="checkbox" name="myCheckbox" checked="checked" value="true" />

Script that does it:

执行此操作的脚本:

$(document).on("click", "[type='checkbox']", function(e) {
        if (this.checked) {
            $(this).attr("value", "true");
        } else {
            $(this).attr("value","false");}
    });

回答by Daniel King

For the MVC Controller method, use a nullable boolean type:

对于 MVC 控制器方法,使用可为空的布尔类型:

public ActionResult Index( string responsables, bool? checkResp) { etc. }

public ActionResult Index(string responsables, bool?checkResp) { etc. }

Then if the check box is checked, checkResp will be true. If not, it will be null.

然后,如果选中该复选框,则 checkResp 将为真。如果没有,它将为空。

回答by Néstor Sánchez A.

None of the previous solutions worked for me. Finally I found that the action should be coded as:

以前的解决方案都不适合我。最后我发现动作应该被编码为:

public ActionResult Index(string MyCheck = null)

and then, when checked the passed value was "on", not "true". Else, it is always null.

然后,当检查传递的值是“on”,而不是“true”。否则,它始终为空。

Hope it helps somebody!

希望它可以帮助某人!

回答by kalpesh patel

<form action="Save" method="post">
 IsActive <input type="checkbox" id="IsActive" checked="checked" value="true" name="IsActive"  />

 </form>

 public ActionResult Save(Director director)
        {
                   // IsValid is my Director prop same name give    
            if(ModelState.IsValid)
            {
                DirectorVM ODirectorVM = new DirectorVM();
                ODirectorVM.SaveData(director);
                return RedirectToAction("Display");
            }
            return RedirectToAction("Add");
        }

回答by kalpesh patel

 public ActionResult Save(Director director)
        {
          // IsActive my model property same name give in cshtml
//IsActive <input type="checkbox" id="IsActive" checked="checked" value="true" name="IsActive" 
            if(ModelState.IsValid)
            {
                DirectorVM ODirectorVM = new DirectorVM();
                ODirectorVM.SaveData(director);
                return RedirectToAction("Display");
            }
            return RedirectToAction("Add");
        }

回答by Omid Soleiman

set value in check box like this :

在复选框中设置值,如下所示:

<input id="responsable" name="checkResp" value="true" type="checkbox" />

change checkResp to nullable property in Your model like this :

在您的模型中将 checkResp 更改为可为空的属性,如下所示:

public Nullable<bool> checkResp{ get; set; }

use ? before checkResp like :

用 ?在 checkResp 之前像:

public ActionResult Index( string responsables, bool ? checkResp)
{
 ......
}