[英]Passing javascript array from view to controller in ASP.Net MVC 5
[英]Passing values to controller from ASP.NET MVC view
我将选中的复选框值发送到我的 controller 时遇到问题,我检查了它们,但没有任何反应。 我只能一个一个地做到这一点,当我重新加载页面时,它已被保存,但我不确定如何将多个选中复选框的值传递回 controller。
这是我的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" />
</div>
这是我的 controller
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;
}
}
这是我的 jquery 和 post 方法。
$('#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' 的复选框。 根据 html,'box' 是表中的 header 行元素。 事件处理程序只向服务器发送一个复选框值。 这意味着编写代码以仅在 header 行复选框上发送选中的事件。
如果要在一个 go 中发送多个复选框值,则需要一个带有单击处理程序的提交按钮,该处理程序遍历表的所有行,收集 idtip 和复选框值并创建一个集合以发送到服务器。 服务器端 controller 也需要将集合作为参数,遍历它,对输入进行一一处理。
如果您有多个复选框,则必须使用 class 名称访问它们,除非它们具有不同的 ID。 您可能希望遍历所有复选框并通过索引获取它们的值
HTML 用于 3 个复选框和按钮
<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);
}
});
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.