Search code examples
ajaxasp.net-corerazor-pages

Is it OK to use AJAX to POST to a Razor page model from another page? (Example)


I try to learn web development, and tested to see if I could use only the POST-side of a Razor page/model for an AJAX-script to upload a file via another razor page and at the same time not treat the "FileUpload"-page as a page.

I will cut down the code, just to show what I mean:

Index.cshtml

@* return false, to prevent rendering of FileUpload.cshtml *@
<form asp-page="./FileUpload" enctype="multipart/form-data" 
    onsubmit="Uploader(this);return false;" method="post">
    ...

<script>
    async function Uploader(element) {
        var result = ...

            try {
                const response = await fetch(element.action, {
                    method: 'POST',
                    body: formData
                }).then(response => response.json())
                    .then(data => ...

FileUpload.cshtml.cs

// Another code checks the file and adds errors to ModelState
public async Task<IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
    ...

Example response in Index.cshtml after posting:

{"file":["File type is not allowed or the signature don't match the extenstion"]}

This works, but I wonder if it is acceptable to do this, or if there are any consequences regarding security, performance, if it is a bad/wrong way of doing it, etc?

Thanks for your time and help.


Solution

  • The primary purpose behind having Razor Pages as endpoints is to generate HTML. If you don't have a requirement for HTML, you should really put your upload handler in a controller, especially if the upload handler is intended to be called from multiple locations in your application.

    As to the security question, you should take the same precautions with handling file upload regardless how you create the endpoint that accepts them. There is unlikely to be any significant difference in performance between a Razor page handler and a controller action.