【发布时间】:2021-09-05 23:32:50
【问题描述】:
我正在使用 ASP.NET MVC Core 3.1 构建一个小型应用程序。
我在视图上显示了几个按钮。每行都有一个按钮。单击一行对应的按钮时,我想获取该行的ID值但不刷新页面。应该使用 AJAX 来完成。
查看代码是这样的:
@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
}
}
【问题讨论】:
-
将
type="submit"更改为type="button"并将$('.ids').click(function(){ ... }更改为$(document).on("click",".ids",function(){ ... })
标签: javascript jquery asp.net-mvc asp.net-core