I am trying to post data using ajax request to Asp.Net Core 2.1 Razor Page.
$.ajax({
type: "POST",
url: "/MyPage",
data: { "Key1": Val1},
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
contentType: false,
processData: false,
success: function (response) {
if (response == "Success")
alert("Successfully saved.");
else {
alert(response);
}
},
error: function (e) {
alert(e.responseText);
}
});
Here everything works well.
Now, I want to pass approx 50 textbox's values, so instead of using data: { "Key1": Val1},
Is there any alternative to bind [BindProperty] class
?
My PageModel looks
[BindProperty]
public InputModel Input { get; set; }
More Info on .cshtml
You can use the serialize method:
$.ajax({
type: "POST",
url: "/MyPage",
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
data: $('#theFormId').serialize(),
success: function (response) {
if (response == "Success")
alert("Successfully saved.");
else {
alert(response);
}
},
error: function (e) {
alert(e.responseText);
}
});
You are setting the wrong header value. Also, don't set the contenttype
to false
. That causes the contenttype
to be set to text/plain
instead of application/x-www-form-urlencoded; charset=UTF-8
which you need to transfer the form values.