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

Posted

技术标签:

【中文标题】将复选框的值传递给 asp.net mvc4 中的控制器操作【英文标题】:Pass values of checkBox to controller action in asp.net mvc4 【发布时间】:2013-09-22 15:37:19 【问题描述】:

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

这是我的看法:

@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>
    </table>

我试试这个:

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

但我收到此错误:

Le dictionnaire de paramètres contient une entrée Null pour le 参数 « checkAct » de type non Nullable « System.Boolean » pour la 方法 « 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。名都 paramètre : 参数

翻译:

参数字典包含一个空条目 不可为空类型“System.Boolean”的“checkAct”参数 方法“System.Web.Mvc.ActionResult 索引(System.String, System.String, Boolean) “in” Project.Controllers.GrapheController "。可选参数必须是引用类型,类型 可以为 Null 或被声明为可选参数。的名字 参数:参数

【问题讨论】:

确保复选框中的值设置为 true 【参考方案1】:

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

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

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

在标记代码中:

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

还有你的动作方法签名:

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

    //Do Something

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

【讨论】:

我尝试过,但一直 checkResp 都有错误值 @Nancy:我已经在我的环境中尝试过它并且它有效。试试这个:使用浏览器上的 F12 开发人员工具查看通过网络传回的值。它是否包含一个名为“checkResp”的值? @Nancy - 好的,如果你检查它,它会说“checkResp=true”。如果不是,您确定您在输入中包含“value="true"' 作为属性吗?它实际上在发送的值中给出了什么值? 优雅而简单。 ++ 如果我没有找到这篇文章,我认为我不会发现 FALSE 值会忽略表单中的字段。谢谢你。【参考方案2】:

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

@Html.CheckBox("checkResp")

创建一个与控制器配合得很好的复选框。

【讨论】:

【参考方案3】:

尝试使用表单集合

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


【讨论】:

这对我帮助很大。我只是想知道它是如何工作的&lt;input value="check1" name="checkboxes" type="checkbox" /&gt; 当我循环通过collection["checkboxes"] 它返回已检查的复选框的值。这是怎么发生的?【参考方案4】:

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

public ActionResult Index(string MyCheck = null)

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

希望对某人有所帮助!

【讨论】:

【参考方案5】:

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

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

&lt;input type="checkbox" name="myCheckbox" checked="checked" /&gt;

但如果你添加了

&lt;input type="checkbox" name="myCheckbox" checked="checked" value="true" /&gt;

执行此操作的脚本:

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

【讨论】:

谢谢马塔斯。设置 value="true" 解决了没有复选框值回传到控制器操作的问题。来自 w3schools.com 关于复选框:对于复选框,值属性的内容不会出现在用户界面中。 value 属性仅在提交表单时才有意义。如果在提交表单时复选框处于选中状态,则复选框的名称与 value 属性的值一起发送(如果未选中复选框,则不发送任何信息)。 w3schools.com/jsref/prop_checkbox_value.asp【参考方案6】:

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

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

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

public Nullable<bool> checkResp get; set; 

使用?在 checkResp 之前:

public ActionResult Index( string responsables, bool ? checkResp)

 ......

【讨论】:

【参考方案7】:

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

public class YourViewModel 
    public bool ConditionaValue  get; set; 

在您看来,您可以创建一个将绑定到此布尔值的复选框:

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

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

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

【讨论】:

我没有使用任何强类型,没有它我可以传递这个值吗?? @Nancy,然后按照 COLT TOLD 回答使用 FormCollection 有时你只是想传递一个值而不是模型绑定的一部分【参考方案8】:

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

public ActionResult Index(string responsables, bool?checkResp) 等等。

然后如果复选框被选中,checkResp 将为真。如果不是,它将为空。

【讨论】:

【参考方案9】:
 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");
        

【讨论】:

【参考方案10】:
<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");
        

【讨论】:

【参考方案11】:

我确实对大多数解决方案都有问题,因为我试图使用具有特定样式的复选框。我需要复选框的值来将它们发送到列表中,一旦收集到值,就需要保存它。一段时间后,我确实设法解决了这个问题。

希望它可以帮助某人。 下面是代码:

控制器:

    [HttpGet]
    public ActionResult Index(List<Model> ItemsModelList)
    

        ItemsModelList = new List<Model>()
                        
            //example two values
            //checkbox 1
            new Model CheckBoxValue = true,
            //checkbox 2
            new Model CheckBoxValue = false

        ;

        return View(new ModelLists
        
            List = ItemsModelList

        );


    

    [HttpPost]
    public ActionResult Index(ModelLists ModelLists)
    
        //Use a break point here to watch values
        //Code... (save for example)
        return RedirectToAction("Index", "Home");

    

模型 1:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;

    namespace waCheckBoxWithModel.Models
    
        public class Model


    public bool CheckBoxValue  get; set; 


    

模型 2:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;

    namespace waCheckBoxWithModel.Models
    
        public class ModelLists


    public List<Model> List  get; set; 


    

查看(索引):

    @
ViewBag.Title = "Index";

@model waCheckBoxWithModel.Models.ModelLists
    
    <style>

.checkBox 
    display: block;
    position: relative;
    margin-bottom: 12px;
    cursor: pointer;
    font-size: 22px;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;


    /* hide default checkbox*/
    .checkBox input 
        position: absolute;
        opacity: 0;
        cursor: pointer;
    

/* checkmark */
.checkmark 
    position: absolute;
    top: 0;
    left: 0;
    height: 25px;
    width: 25px;
    background: #fff;
    border-radius: 4px;
    border-width: 1px;
    box-shadow: inset 0px 0px 10px #ccc;


/* On mouse-over change backgroundcolor */
.checkBox:hover input ~ .checkmark 
    /*background-color: #ccc;*/


/* background effect */
.checkBox input:checked ~ .checkmark 
    background-color: #fff;


/* checkmark (hide when not checked) */
.checkmark:after 
    content: "";
    position: absolute;
    display: none;


/* show checkmark (checked) */
.checkBox input:checked ~ .checkmark:after 
    display: block;


/* Style checkmark */
.checkBox .checkmark:after 
    left: 9px;
    top: 7px;
    width: 5px;
    height: 10px;
    border: solid #1F4788;
    border-width: 0 2px 2px 0;
    -webkit-transform: rotate(45deg);
    -ms-transform: rotate(45deg);
    transform: rotate(45deg);

   </style>

    @using (Html.BeginForm())
    

    <div>

@
    int cnt = Model.List.Count;
    int i = 0;



@foreach (var item in Model.List)


    
        if (cnt >= 1)
         cnt--; 
    

    @Html.Label("Example" + " " + (i + 1))

    <br />

    <label class="checkBox">
        @Html.CheckBoxFor(m => Model.List[i].CheckBoxValue)
        <span class="checkmark"></span>
    </label>

     i++;

    <br />



<br />
<input type="submit" value="Go to Post Index" />    

    </div>

    

【讨论】:

【参考方案12】:

我希望这会有所帮助。

为您的视图创建一个视图模型。这将代表复选框的真或假(选中或未选中)值。

public class UsersViewModel

    public bool IsAdmin  get; set; 
    public bool ManageFiles  get; set; 
    public bool ManageNews  get; set; 

接下来,创建您的控制器并将视图模型传递给您的视图。

public IActionResult Users()

     var viewModel = new UsersViewModel();
     return View(viewModel);

最后,创建您的视图并引用您的视图模型。使用@Html.CheckBoxFor(x => x) 来显示复选框并保存它们的值。

@model Website.Models.UsersViewModel
<div class="form-check">
    @Html.CheckBoxFor(x => x.IsAdmin)
    <label class="form-check-label" for="defaultCheck1">
           Admin
    </label>
</div>
          

当您从视图发布/保存数据时,视图模型将包含复选框的值。请务必将视图模型作为参数包含在调用以保存数据的方法/控制器中。

我希望这是有道理的并有所帮助。这是我的第一个答案,如果缺少,请见谅。

【讨论】:

以上是关于将复选框的值传递给 asp.net mvc4 中的控制器操作的主要内容,如果未能解决你的问题,请参考以下文章