每次执行代码都会收到错误消息。对于表中的第一行,错误消息为:
错误id=1url出错:
/Person/Index?handler=DeleteById&id=1
正如你在评论过的javascript中看到的那样,我尝试使用了几个url,但是没有一个能正常工作,我也遇到了同样的错误。
我相信这应该很容易,但我错过了一些东西。有人能帮我吗?
提前谢谢!
我的索引.cshtml:
@page
@model WebApplication20.Pages.Person.IndexModel
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
@{
ViewData["Title"] = "Index";
}
<h1>Index</h1>
<p>
<a asp-page="Create">Create New</a>
</p>
<div id="msg"></div>
<table class="table">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.Person[0].PersonName)
</th>
<th>
@Html.DisplayNameFor(model => model.Person[0].PersonAddress)
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model.Person)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.PersonName)
</td>
<td>
@Html.DisplayFor(modelItem => item.PersonAddress)
</td>
<td>
<button class="btn btn-danger" onclick="DeleteId('@item.PersonId');">Delete</button>
</td>
</tr>
}
</tbody>
</table>
Javascript(嵌入
<script>
标签(在页面底部)
function DeleteId(id) {
var options = {};
//options.url = "/Person/Index?id=" + id + "&handler=DeleteById";
//options.url = "/Index?id=" + id + "&handler=DeleteById";
options.url = "/Person/Index?handler=DeleteById&id=" + id;
options.type = "POST";
options.headers = {
RequestVerificationToken:
$('input:hidden[name="MY-XSRF-TOKEN"]').val()
};
options.success = function (data) {
$("#msg").html("Great Success!");
};
options.error = function () {
$("#msg").html("Error something went wrong with id = " + id + "url: " + options.url);
};
$.ajax(options);
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using WebApplication20.Data;
using WebApplication20.Models;
namespace WebApplication20.Pages.Person
{
public class IndexModel : PageModel
{
private readonly WebApplication20.Data.ApplicationDbContext _context;
public IndexModel(WebApplication20.Data.ApplicationDbContext context)
{
_context = context;
}
public IList<Models.Person> Person { get;set; }
public async Task OnGetAsync()
{
Person = await _context.Person.ToListAsync();
}
public IActionResult OnPostDeleteById(int id)
{
var pers = _context.Person.Find(id);
_context.Remove(pers);
_context.SaveChanges();
Person = _context.Person.ToList();
return Page();
}
}
}