如何解决将值从 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" />
</div>
这是我的控制器
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”的复选框的点击处理程序。根据 html,'box' 是表格中的标题行元素。事件处理程序只向服务器发送一个复选框值。这意味着代码被编写为仅在标题行复选框上发送选中的事件。
如果您想一次性发送多个复选框值,您需要一个带有单击处理程序的提交按钮,该处理程序遍历表的所有行,收集 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);
}
});
});
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。