I’m trying to pass the EmployeeId of the row I click to the jQuery statement, but I get null
everytime.
I would appreciate to know what am I doing wrong.
Checkout my below Code :
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>
Employee Controller
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());
}
}
Given an ID,the ExecuteSP method sets the column IsDelete to 2 . But as I said I just get a null
ID everytime.
2
Answers
In controller, You are expecting
id
name, So you need rename fromEmployeeId
toid
like below.The ID attribute in each page should be unique, hence using
#BtnId
is incorrect because ID is repeating. Add BtnId to the class attribute and addEmployeeId
todata-id
attribute instead. See the code below.Then in your script, it’s better to bind the event to the button; Use
$(this).data("id")
and assign it to the variable EmployeeId which we will use in ajax.