![](/img/trans.png)
[英]How to Pass default values as False of checkBox to controller action in asp.net mvc4
[英]Pass values of checkBox to controller action in asp.net mvc4
我想測試是否從我的操作方法中選中了復選框,我需要的是將復選框值從視圖傳遞到控制器。
這是我的觀點:
@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 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 : 參數
你能幫我嗎 !
如果選中復選框,則回發值將包含[InputName]=[InputValue]
形式的鍵值對
如果未選中復選框,則發布的表單根本不包含對該復選框的引用。
知道這一點,以下將起作用:
在標記代碼中:
<input id="responsable" name="checkResp" value="true" type="checkbox" />
以及您的操作方法簽名:
public ActionResult Index( string responsables, bool checkResp = false)
這將工作,因為選中復選框時,回后將包含checkResp=true
,如果未選中該復選框,則參數將默認為false。
出於某種原因,Andrew 使用 Mvc 5 手動創建復選框的方法對我不起作用。相反,我使用了這個
@Html.CheckBox("checkResp")
創建一個復選框,可以很好地與控制器配合使用。
嘗試使用表單集合
<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);
}
}
以前的解決方案都不適合我。 最后我發現動作應該被編碼為:
public ActionResult Index(string MyCheck = null)
然后,當檢查傳遞的值是“on”,而不是“true”。 否則,它始終為空。
希望它可以幫助某人!
如果您希望在提交表單時由 MVT 控制器讀取您的值,並且您不知道如何處理隱藏的輸入。 您可以做的是將value
屬性添加到您的checkbox
並將其設置為true
或false
。
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");}
});
在復選框中設置值,如下所示:
<input id="responsable" name="checkResp" value="true" type="checkbox" />
在您的模型中將 checkResp 更改為可為空的屬性,如下所示:
public Nullable<bool> checkResp{ get; set; }
采用 ? 在 checkResp 之前像:
public ActionResult Index( string responsables, bool ? checkResp)
{
......
}
你應該強烈地輸入你的觀點。 然后你可以這樣做:
public class YourViewModel {
public bool ConditionaValue { get; set; }
}
在您的視圖中,您可以創建一個復選框來綁定到這個布爾值:
@Html.CheckBoxFor(x => x.ConditionalValue)
如果選中,則模型屬性將為真。
但是,對於您的直接問題.. 您需要將復選框命名為與您的操作方法參數相同的名稱.. 它們應該是bool
..
對於 MVC 控制器方法,使用可為空的布爾類型:
public ActionResult Index(string responsables, bool?checkResp) { etc. }
然后,如果選中該復選框,則 checkResp 將為真。 如果沒有,它將為空。
<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");
}
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");
}
我確實遇到了大多數解決方案的問題,因為我試圖使用具有特定樣式的復選框。 我需要復選框的值來將它們發送到列表中,一旦收集了值,就需要保存它。 一段時間后,我確實設法解決了它。
希望它可以幫助某人。 這是下面的代碼:
控制器:
[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>
}
我希望這會有所幫助。
為您的視圖創建一個視圖模型。 這將代表復選框的真或假(選中或未選中)值。
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>
當您從視圖中發布/保存數據時,視圖模型將包含復選框的值。 確保將視圖模型作為參數包含在被調用以保存數據的方法/控制器中。
我希望這是有道理的並有所幫助。 這是我的第一個回答,如有不足請見諒。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.