4

I'm working with an ASP.NET Core RazorPage as an alternative to an MVC controller, and I want to be able to submit the client side form via XMLHttpRequest. I've already figured out the XSRF token bits so that passes the muster, but the RazorPages framework doesn't seem to process the inbound JSON payload and bind it to the property as expected.

Some code:

The page's model (.cshtml.cs):

public class IndexModel : PageModel
{
    private Database database;
    private ILogger logger;

    [BindProperty]
    public AddRequestModel MyRequest { get; set; }

    public IndexModel(Database database, ILogger<IndexModel> logger)
    {
        this.database = database;
        this.logger = logger;
    }

    public void OnGet() {}

    public IActionResult OnPostValidate()
    {
        if (ModelState.IsValid)
        {
            // ...
        }

        return new BadRequestObjectResult(ModelState);
    }

    public async Task<IActionResult> OnPutConfirmAsync()
    {
        // ...
    }
}

And the client side post:

const url = "?handler=validate";
const data = { MyRequest: this.fields };
await axios.post(url, data);

I have verified the data is being submitted correctly:

enter image description here

That X-XSRF-TOKEN header is being added by axios before the request is submitted. The fact that the server responds with a list of errors indicates that it's not the XSRF token causing the problem:

enter image description here

Note the MyRequest object does not contain the values from the request payload - it was not bound as expected (FirstName would not return a required error otherwise). How can I tell RazorPages to accept the JSON request and bind it to my property?

Chris
  • 27,596
  • 25
  • 124
  • 225

3 Answers3

1

I was able to get the Binding works by adding FromBody similar to how it worked for ASP.NET Web API 2.

    [BindProperty, FromBody]
    public BroadcastMessageEditingViewModel BindingInfo { get; set; }
Luke Vo
  • 17,859
  • 21
  • 105
  • 181
0

Use urlsearchparams with formdata.

In this post you can find more information How do I post form data with fetch api?

julian zapata
  • 89
  • 1
  • 8
-2

You would be better off posting your data to an API endpoint instead of a page controller. Create a class from ControllerBase and it will handle your JSON post correctly.

Jeff S
  • 554
  • 5
  • 13
  • That *may* be the case, but this was an *experiment*, and is over a year old. Stackoverflow is for answering questions, not redirecting to alternatives. – Chris Jan 18 '19 at 09:14