ajax 调用的处理程序方法中的 BindingProperty 为 null

BindingProperty is null in handler method called by ajax

在 Razor 页面中,我想更改实体的数据。数据在 OnGet 中加载并保存在 OnPost 中。在 OnGet 中加载的数据保存到名为 Person 的 属性 中。稍后我可以简单地在 OnPost 中检索它们(这是相同的对象)。

但是,如果我使用由 Ajax 调用调用的处理程序,属性 对象会被初始化(整数属性为 0,对象属性为零)但它不再是原始对象.

我必须做什么才能使原始对象在 Ajax 调用调用的处理程序中也可用?

我已经尝试使用 [BindProperty] 属性并在 razor 页面中使用隐藏输入。或者访问 ViewData.Model 但是是行不通的。 Person 模型的其他数据仍然是 null。

Ajax-通话:

function addEntitlement() {
        var vacationEntitlement = {};
        vacationEntitlement["Year"] = $('#newEntitlementYear').val();
        vacationEntitlement["Days"] = $('#newEntitlementDays').val();
        vacationEntitlement["PersonID"] = $('#hiddenPersonID').val();
        $.ajax({
            type: "POST",
            url: "./Edit?handler=AddEntitlement",
            beforeSend: function (xhr) {
                xhr.setRequestHeader("XSRF-TOKEN",
                    $('input:hidden[name="__RequestVerificationToken"]').val());
            },
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: JSON.stringify(vacationEntitlement)
        }).fail(function () {
            alert('error');
        }).done(function () {
        });
    }

页面模型:

    public IActionResult OnGet(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        Person = _unitOfWork.PersonRepository.GetByID(id);

        if (Person == null)
        {
            return NotFound();
        }

        return Page();
    }

    public JsonResult OnPostAddEntitlement([FromBody] VacationEntitlement vacationEntitlement)
    {
      ///Tried to acces Person or ViewData.Model.Person here.
      ///But Person is just intialized but does not contain the expected data.
    }

尝试使用 TempData 它允许您将数据从一个动作传递到另一个动作

Person = _unitOfWork.PersonRepository.GetByID(id);
TempData["Person"] = Person

然后

public JsonResult OnPostAddEntitlement([FromBody] VacationEntitlement vacationEntitlement)
{
   if(TempData.ContainsKey("Person")) {
     var person = TempData["Person"] as Person; /* (as Person} I just assume the class name is Person */
     // place your logic here
   }
}

并确保正确设置您的 TempData 配置 https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-2.2#tempdata