Razor Pages AJAX-在AJAX删除调用后填充模型

时间:2019-03-07 21:37:46

标签: c# ajax razor-pages

我是AJAX的新手,正在尝试删除表中的一行而不刷新整个页面。单击按钮后,该行已成功从数据库中删除,但出现此错误:

  

NullReferenceException:对象引用未设置为的实例   对象。

表示模型为空。我不知道在AJAX调用后应该如何再次填充模型。

有人处理过吗?

我的模型班:

public class Person
{
    public int PersonId { get; set; }
    public string PersonName { get; set; }
    public string PersonAddress { get; set; }
}

我的Index.cshtml.cs:

[ValidateAntiForgeryToken]
    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 new JsonResult
                ("Customer Deleted Successfully!");
        }
    }

我的Index.cshtml:

@page
@model WebApplication20.Pages.Person.IndexModel

<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>
                    <form method="post">
                    <button class="btn btn-danger" onclick="DeleteId('@item.PersonId');">Delete</button>
                    </form>

                </td>
            </tr>
        }
    </tbody>
</table>

Javascript(嵌入在页面底部的script标签中)

<script>
    function DeleteId(id) {
        var options = {};

        options.url = "/Person/Index?handler=DeleteById&id=" + id;
        options.beforeSend = function(xhr) {
            xhr.setRequestHeader("MY-XSRF-TOKEN",
                $('input:hidden[name="__RequestVerificationToken"]').val());
        };
        options.dataType = "json";
        options.type = "POST";

        options.success = function (data) {
            $("#msg").html("Great Success");
        };

        options.error = function () {
            $("#msg").html("Error something went wrong");
        };
        $.ajax(options);
    }

</script>

0 个答案:

没有答案