从ASP.NET MVC视图向控制器传递值



我在将选中的复选框值发送到控制器时遇到问题,我检查了所有复选框值,但什么都没有发生。我只能一个接一个地这样做,当我重新加载页面时,它已经被保存了,但我不知道如何将多个复选框的值传递回控制器。

这是我的cshtml。

<table class="table table-striped grid-table">
<tr>
<th>Samp</th>
<th>Id of Book</th>
<th>
<input type="checkbox"  id="box" name="checkAll" />
</th>
</tr>
@foreach (var item in (IEnumerable<cit.Models.getCheIdTip_Result>)Model)
{
<tr>
<td>@item.idtip</td>
<td>@item.tipname</td>
<td>
<div class="pure-checkbox">
<input type="checkbox" idtip="@item.idtip" class="checktip" checked="@(item.idemployee == ViewBag.idemployee ? true : false)" name="@item.id.ToString()" id="@item.id.ToString()" />
<label for="@item.id.ToString()"></label>
</div>
</td>
</tr>
}
</table>
<input type="hidden" value="@ViewData["idemployee"]" name="idemployee" id="idemployee" class="idemployee" />   

这是我的控制器

public JsonResult CheckUsers(int idemployee, int idtip, bool che)
{
try
{
if (che)
{
checkusers cheuser = new checkusers();
cheuser.idemployee = idemployee;
cheuser.idtip = idtip;
Database.checkusers.Add(cheuser);
Database.SaveChanges();
}
else if (!che)
{
var cheuserdelete = Database.checkusers.Where(a => a.idemployee == idemployee && a.idtip == idtip).FirstOrDefault();
Database.checkusers.Remove(cheuserdelete);
Database.SaveChanges();
}
if (Request.IsAjaxRequest())
{
return Json(true, JsonRequestBehavior.AllowGet);
}
else
{
return Json(true, JsonRequestBehavior.AllowGet);
}
}
catch (Exception ex)
{
Logger.Error("Error: {0}", ex.ToString());
return null;
}
}

这是我的带有post方法的jquery。

$('#box').click(function () {
$('.checktip').prop('checked', true);
var idemployee = $('.idemployee').val();
var idtip = $(this).attr('idtip');
var che = $(this).prop('checked');
$.ajax({
url: UrlSettingsDocument.EmpTipes,
data: { idemployee: idemployee, idtip: idtip, che: che },
type: "POST",
success: function (result) {
if (result.result == "Redirect") {
window.location = result.url;
}
}
});
});

您的jQuery代码有一个id为'box'的复选框的点击处理程序。'box’是根据html在表中的头行元素。事件处理程序只向服务器发送一个复选框值。这意味着编写代码的目的是只发送标题行复选框上的选中事件

如果您想一次发送多个复选框值,您需要一个带有点击处理程序的提交按钮,该按钮会遍历表的所有行,收集idtip和复选框值并创建一个集合发送到服务器。服务器端控制器还需要将集合作为参数,并对其进行迭代以逐个处理输入。

如果有多个复选框,则必须使用类名访问它们,除非它们具有不同的id。您希望循环浏览所有复选框,并通过索引获得它们的值

用于3个复选框和按钮的HTML

<div class="row">
Bike <input type="checkbox" class="chkbox" value="Bike" />
Car <input type="checkbox" class="chkbox" value="Car" />
Boat <input type="checkbox" class="chkbox" value="Boat" />
</div>  
<div class="row">
<input type="button" id="btnSubmitCB" value="Submit" />
</div>

JQuery

$(document).ready(function () { 
$('#btnSubmitCB').click(function () {
$('input[type=checkbox]').each(function () {
if (this.checked) {
var ckbIndex = $('.chkbox').index(this);
var cbValue = $('.chkbox').eq(ckbIndex).val();
console.log(cbValue);
}
});        
});
});

最新更新