通过AJAX方式点击按钮获取ID



我正在使用ASP.NET MVC Core 3.1构建一个小型应用程序。

我在视图上显示了几个按钮。每一行都有一个按钮。当单击对应于一行的按钮时,我希望获得该行的ID值,但不刷新页面。应该使用AJAX来完成。

View代码是这样的:

@using Updater.Models
@model IEnumerable<TemplateData> 
@{
Layout = null;
}

@{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
@if (Model.Count() > 0)
{
<hr />
<table cellpadding="0" cellspacing="0" border="1" style="height:600px">
<tr>
<th>ID</th>
<th>Location</th>
<th>Observation Type</th>
<th>EmpName</th>
<th>Status</th>
</tr>
@foreach (TemplateData sheet in Model)
{
<tr>
<td>@sheet.ID</td>
<td>@sheet.Location</td>
<td>@sheet.ObservationType</td>
<td>@sheet.EmpName</td>
<td>
@Html.DropDownList("CI Status", new List<SelectListItem>
{
new SelectListItem{ Text="", Value = "0" },
new SelectListItem{ Text="Completed", Value = "1" },
new SelectListItem{ Text="In-Progress", Value = "2" },
new SelectListItem{ Text="Review", Value = "3" },
})
</td>
</tr>
<tr>
<td>
@using (Html.BeginForm("Index", "sheet", FormMethod.Post))
{
<input type="submit" value="Update Status" class="ids" data-id="@sheet.ID" />
}
</td>
</tr>
}
</table>
}
</div>
<script type="text/javascript">
$('.ids').click(function() {
var rowID = $(this).data('id');
alert(rowID);
});
</script>

**已编辑**

在继续Costa下面建议的从Javascript调用控制器的过程中,我尝试了下面的代码,但它并没有显示消息,而是指向URL:http://localhost/sheet

<tr>
<td>
@using (Html.BeginForm("Index", "sheet", FormMethod.Post))
{
<input type="submit" id="btnSubmit" value="Update Status" class="ids" data-id="@sheet.ID" onClick="UpdateStatus(@sheet.ID)"/>
}
</td>
</tr>
}
</table>
}
</div>
<script type="text/javascript">
$.ajax({
type: "POST",
url: '@Url.Action("Home", "UpdateStatus")',
contentType: "application/json; charset=utf-8",
data: id,
dataType: "json",
success: function() { alert('Success'); },
error: function() { alert('Error'); }
});
</script>

控制器代码

public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
[HttpPost]
[Route("UpdateStatus")]
public void UpdateStatus()
{
//Do Something
}
}

如果您想将ID传递给javascript,可以使用以下方法:

<input type="submit" value="Update Status" class="ids" data-id="@sheet.ID" onClick="UpdateStatus(@sheet.ID)" />

<script>
function UpdateStatus(string id) {
$.ajax({
type: "POST",
url: "/UpdateStatus",
contentType: "application/json; charset=utf-8",
data: {"id": id},
dataType: "json",
success: function() { alert('Success'); },
error: function() { alert('Error'); }
});
}
</script>

最后,像这样编辑你的控制器:

[HttpPost]
[Route("UpdateStatus/{id}")]
public void UpdateStatus(string id)
{
//Do Something
}

最新更新