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

时间:2013-09-18 01:58:14

标签: c# asp.net asp.net-mvc asp.net-mvc-4 checkbox

我想测试是否从我的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>

我尝试了:

 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 dictionnairedeparamètresconientuneentréeNullpourleparamètre«checkAct»de type non Nullable«System.Boolean»pourlaméthode«System.Web.Mvc.ActionResult Index(System.String,System.String,Boolean)» dans«Project.Controllers.GrapheController»。 Unparamètrefacultatifdoitêtreuntyperéférence,un type Nullableouêtredéclaréentantqueparamètrefacultatif。 Nomduparamètre:参数

你能帮帮我吗?

12 个答案:

答案 0 :(得分:60)

如果选中了复选框,则回发值将包含[InputName]=[InputValue]

形式的键值对

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

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

在标记代码中:

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

你的行动方法签名:

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

这样做会有效,因为选中复选框后,回发将包含checkResp=true,如果未选中该复选框,则参数将默认为false。

答案 1 :(得分:13)

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

@Html.CheckBox("checkResp")

创建一个可以与控制器配合使用的复选框。

答案 2 :(得分:9)

尝试使用表单集合

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

}

答案 3 :(得分:3)

如果您希望在提交表单时MVT控制器读取您的值,而您没有处理隐藏输入的内容。您可以执行的操作是将value属性添加到checkbox并将其设置为truefalse

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

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

但是如果你添加

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

执行此操作的脚本:

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

答案 4 :(得分:3)

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

//Global variable 
int previousPosition = 0;
.
.
.
mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(final int position) {
            if(previousPosition < position){
              Intent intent = new Intent(MainActivity.this, Main2Activity.class);
              startActivity(intent);
             }
             previousPosition = position;
        }
    });

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

Hope it helps somedby.

答案 5 :(得分:0)

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

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

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

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

如果选中,则model属性为true。

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

答案 6 :(得分:0)

对于MVC Controller方法,使用可以为空的布尔类型:

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

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

答案 7 :(得分:0)

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

答案 8 :(得分:0)

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

答案 9 :(得分:0)

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

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

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

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

使用?在checkResp之前:

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

答案 10 :(得分:0)

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

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

控制器:

    [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>

    }

答案 11 :(得分:0)

我希望这会有所帮助。

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

Pair *pairFactory()
{
  return new Pair{};
}

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

int main() {
  Pair* p = pairFactory();

  // This function call should work without crashing:
  p->check();

  // Deallocating the heap memory. (Assuming it was made on the heap!)
  delete p;

  std::cout << "If you can see this text, the system hasn't crashed yet!" << std::endl;
}

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

std::unique_ptr<Pair> pairFactory()
{
    return std::make_unique<Pair>();
}

int main() {
    auto p = pairFactory();

    p->check();
    std::cout << "If you can see this text, the system hasn't crashed yet!" << std::endl;
}

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

我希望这是有道理的,对您有所帮助。这是我的第一个答案,如果缺少的话,抱歉。

相关问题