In a Razor page I want to change the data of an entity. The data is loaded in OnGet and saved in OnPost. The data that is loaded in OnGet is saved to a property called Person. At a later time I can simply retrieve them in OnPost (it's the identical object).
However, if I use a handler called by an Ajax call, the property object is initialized (integer properties are 0, object properties are zero) but it is not the original object anymore.
What do I have to do so that the original object is also available in the handler called by the Ajax call?
I already tried to use [BindProperty] attribute and to use a hidden input in the razor page. Or to access ViewData.Model But is does not work. Person and other data of the model is still kind of null.
Ajax-Call:
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 () {
});
}
PageModel:
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.
}
Personfrom OnGet to be access in OnPostAddEntitlement? - John VelasquezPersonis accessable in OnGet and in OnPost at the moment. But not in OnPostAdd but it should be. - Wayn0rSessionorTempData.TempDatais just a specialized form ofSessionthat removes values after they're accessed, whereas normal session state would persist for the life of the session. - Chris Pratt