Doidel
Doidel

Reputation: 319

razor named handler and BindProperty

I am trying to send an ajax post request to a razor page. This razor page has some public properties with [BindProperty]. For the ajax request I am trying to use a named handler.

@page "{title}"

[BindProperty]
public BookViewModel BookModel { get; set; }

public IActionResult OnPostMarkdownInput(string title)
{
    return new EmptyResult();
}

On the client side, sending empty data (+ /title) ends in a BadRequest. But sending it with the form that binds BookModel works. My suspicion was therefore that [BindProperty] requires this property to be bound even for the namedHandler. But the problem persisted even after removing it.

How can I add a namedHandler that does not require any properties to be bound? Or why do I get a BadRequest when no data is sent?

Thanks!

Upvotes: 0

Views: 249

Answers (1)

Mike Brind
Mike Brind

Reputation: 30065

A Bad Request response from an AJAX-initiated request in Razor Pages is usually the symptom of a missing Request Verification token, which you need to include either as a form value or a header depending on the type of request you are making. If you are posting JSON, you need to add a header:

$.ajax({
    type: "POST",
    headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
    url: "/yourformhandler",
    ...

Otherwise you just need to ensure that the hidden field is included in the posted values.

See more about Request Verification here: https://www.learnrazorpages.com/security/request-verification

Upvotes: 1

Related Questions