如何将 Id 传递给 Jquery 语句 - ASP.NET MVC



我试图将我单击的行的 EmployeeId 传递给 jQuery 语句,但每次都得到null。 我很想知道我做错了什么。

查看我的以下代码:

Index.cshtml

@using (Html.BeginForm("Index", "Employee", FormMethod.Post, new { @id = "myForm" }))
{
<table class="table">
-- headers

@foreach (var item in Model)
{

<tr>

<td> <button class="btn btn-success" id="BtnId" onclick="Update(@item.EmployeeId)"><i class="fa fa-toggle-on"></i></button> </td>
<td>
@Html.DisplayFor(modelItem => item.EmployeeId)
</td>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.DepartmentId)
</td>
<td>
@Html.DisplayFor(modelItem => item.Address)
</td>
<td>
@Html.DisplayFor(modelItem => item.IsDeleted)
</td>

</tr>

}
</table>
}
<script>
$(document).ready(function () {
var Update = function (EmployeeId) {



$("#BtnId").on('click', function () {
var myformdata = $("#myForm").serialize();

$.ajax({
type: "POST",
url: "Employee/Index?EmployeeId="+EmployeeId,
data:myformdata,
success: function () {

}
});


});
}
});
</script>

员工控制器

public class EmployeeController : Controller
{
EmployeeModule EM = new EmployeeModule();
public ActionResult Index()
{
return View(EM.List());
}

[HttpPost]
public ActionResult Index(int id)
{


bool a = EM.ExecuteSP(id);
return View(EM.List());
}
}

给定一个 ID,ExecuteSP 方法将列 IsDelete 设置为 2 。但正如我所说,我每次都会得到一个null身份证。

在控制器中,您期望id名称,因此您需要从EmployeeId重命名为id,如下所示。

$(document).ready(function () {
var Update = function (EmployeeId) {
$.ajax({
type: "POST",
url: "Employee/Index",
data: {id: EmployeeId},
success: function () {
}
});
}
});

每个页面中的 ID 属性应该是唯一的,因此使用#BtnId是不正确的,因为 ID 是重复的。将 BtnId 添加到类属性,并改为将EmployeeId添加到data-id属性。请参阅下面的代码。

@foreach (var item in Model)
{
<tr>
<td>
<button class="btn btn-success BtnId" data-id="@item.EmployeeId"><i class="fa fa-toggle-on"></i></button>
</td>
<td>
@Html.DisplayFor(modelItem => item.IsDeleted)
</td>
</tr>
}

然后在脚本中,最好将事件绑定到按钮;使用$(this).data("id")并将其分配给我们将在 ajax 中使用的变量 EmployeeId。

$(document).ready(function () {
var EmployeeId = $(this).data("id");
$(document).click(".BtnId",function(){
$.ajax({
type: "POST",
url: "Employee/Index",
data: {id: EmployeeId},
success: function () {
}
});
});

最新更新