将checkBox的值传递给asp.net mvc4中的控制器操作

Nan*_*ncy 28 c# asp.net checkbox asp.net-mvc asp.net-mvc-4

我想,如果该复选框是从我acion methon检查或不考,我需要的是从视图控制器通过复选框值

这是我的看法

   @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>
Run Code Online (Sandbox Code Playgroud)

我试着这样做:

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

    }
Run Code Online (Sandbox Code Playgroud)

,但我有这个错误:

乐德辞典参数应用contient UNE主菜空倒乐paramètre«checkAct»德式非可空«System.Boolean»倒拉METHODE«System.Web.Mvc.ActionResult指数(System.String,System.String,布尔)»丹斯«项目.Controllers.GrapheController».联合国paramètrefacultatif DOIT理由取消类型引用,联合国可空类型鸥理由宣布EN坦阙paramètrefacultatif.Nomduparamètre:参数

你能帮我吗 !

And*_*erd 64

如果选中复选框,则回发值将包含表单的键值对 [InputName]=[InputValue]

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

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

在标记代码中:

 <input id="responsable" name="checkResp" value="true" type="checkbox" />
Run Code Online (Sandbox Code Playgroud)

而你的行动方法签名:

public ActionResult Index( string responsables, bool checkResp = false)
Run Code Online (Sandbox Code Playgroud)

这将起作用,因为当选中复选框时,回发将包含checkResp=true,如果未选中该复选框,则参数将默认为false.

  • 我试试,但是整个时间checkResp都有假值 (3认同)

Phi*_*tle 14

出于某种原因,安德鲁手工创建复选框的方法对我来说不适合使用Mvc 5.相反,我使用了这个

@Html.CheckBox("checkResp")
Run Code Online (Sandbox Code Playgroud)

创建一个与控制器配合良好的复选框.


COL*_*OLD 12

尝试使用表单集合

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

}
Run Code Online (Sandbox Code Playgroud)


Nés*_* A. 5

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

public ActionResult Index(string MyCheck = null)
Run Code Online (Sandbox Code Playgroud)

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

希望它可以帮助某人!