将CheckBox的值传递给ASP.NET MVC4中的控制器操作 [英] Pass values of checkBox to controller action in asp.net mvc4
问题描述
我想测试是否从我的操作方法中选中了该复选框,我需要的是将复选框值从视图传递到控制器.
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.
这是我的观点:
@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>
我尝试:
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);
}
但是我收到此错误:
无内容参数字典Null pour leparamètre«checkAct»de type non Nullable«System.Boolean»方法«System.Web.Mvc.ActionResult Index(System.String,System.String,Boolean)» dans«Project.Controllers.GrapheController».取消参数化类型,取消参数化类型的可空输出或取消声明. 参数规范:参数
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
能帮我吗!
推荐答案
如果选中了复选框,则回发值将包含格式为[InputName]=[InputValue]
If a checkbox is checked, then the postback values will contain a key-value pair of the form [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:
在标记代码中:
<input id="responsable" name="checkResp" value="true" type="checkbox" />
以及您的操作方法签名:
And your action method signature:
public ActionResult Index( string responsables, bool checkResp = false)
这将起作用,因为选中此复选框时,回发将包含checkResp=true
,如果未选中此复选框,则参数默认为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.
这篇关于将CheckBox的值传递给ASP.NET MVC4中的控制器操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!