Learning
Learning

Reputation: 20011

Multiple submit button fail to find the handler method in asp.net core 3.1 razor page application

I have a single form which has two button one to upload image using ajax call & other is main submit button which saves all the data.

I am still very new to asp.net core and trying different thing to learn asp.net core with razor page.

I read lot of article about multiple form submit but most of then where using two form with submit button for each.

My issue is when i hit the submit button it fails to find the handler method, after full days troubleshoot nothing worked and last few article point to error/failure to antiforgery, i not sure how to implement it in below code as i tried few but they gave error may be article where old referencing core 2.2 etc example1 example2

I am not sure about the what exactly is causing the issue any help would be appreciate.

I am trying to upload Image using Ajax method in asp.net core Razor pages, I am main form in will all input fields are kept and with the form for Fileupload i am also added addition button which is for file upload using Ajax, When i hit the

<input type="submit" value="Upload Image" asp-page-handler="OnPostUploadImage" id="btnUploadImage" />

i want it to call OnPostUploadImage method in pageModel file but it alway goes to default OnPost method. when i rename the OnPost to OnPost2 nothing happend..

How can i call OnPostUploadImage() on button btnUploadImage click event.

When i hit click btnUploadImage it generates following error on browser console

Error in FF

XML Parsing Error: no root element found Location: https://localhost:44364/Admin/News/NewsCreate?handler=OnPostUploadImage Line Number 1, Column 1:

Error in Chrome

jquery.min.js:2 POST https://localhost:44364/Admin/News/NewsCreateMultipleSubmit?handler=OnPostUpLoadImage 400 (Bad Request)

event though path looks fine but it cant find it as per error message

 @page
    @model BookListRazor.Pages.Admin.News.NewsCreateModel
    @{
        ViewData["Title"] = "News Create";
        Layout = "~/Pages/Shared/_LayoutAdmin.cshtml";
    }


     <div class="border container" style="padding:30px;">
            <form method="post" enctype="multipart/form-data">
                <div class="text-danger" asp-validation-summary="ModelOnly"></div>
                <input hidden asp-for="News.NewsImage" />
                <input id="fileName" hidden value="" />

                <div class="form-group row">
                    <div class="col-2">
                        <label asp-for="News.NewsHeading"></label>
                    </div>
                    <div class="col-10">
                        <input asp-for="News.NewsHeading" class="form-control" />

                    </div>
                    <span asp-validation-for="News.NewsHeading" class="text-danger"></span>
                </div>


                <div class="form-group row">
                    <div class="col-2">
                        <label asp-for="News.NewsImage"></label>
                    </div>
                    <div class="col-10">
                        @*<input asp-for="News.NewsImage" type="file" class="form-control" id="NewsImage">*@
                        @*Photo property type is IFormFile, so ASP.NET Core automatically creates a FileUpload control  *@
                        <div class="custom-file">
                            <input asp-for="NewsImageForUpload" class="custom-file-input form-control">
                            <label class="custom-file-label">Click here to change photo</label>
                                                <input type="submit" value="Upload Image" asp-page-handler="OnPostUploadImage" id="btnUploadImage" />

                        </div>
                    </div>
                    <span id="imageStatus" class="text-danger"></span>
                    <span asp-validation-for="NewsImageForUpload" class="text-danger"></span>
                </div>


                <div class="form-group row">
                    <div class="col-3 offset-3">
                        <input id="btnSave" type="submit" value="Create" class="btn btn-primary form-control" />
                    </div>
                    <div class="col-3">
                        <a asp-page="Index" class="btn btn-success form-control">Back to List</a>
                    </div>
                </div>
            </form>
            <script src="~/lib/jquery/dist/jquery.min.js"></script>
            <script src="https://cdn.ckeditor.com/4.14.0/full/ckeditor.js"></script>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
            <script>

                $(document).ready(function () {

                    $("#btnSave").addClass("disable-button");

                    $('.custom-file-input').on("change", function () {
                        var fileName = $(this).val().split("\\").pop();
                        $(this).next('.custom-file-label').html(fileName);
                        $("#fileName").val(fileName);
                        $("#btnSave").removeClass("disable-button");
                    });

                    if ($("#fileName").val() == "") {
                        //alert("Select Image...");;
                    }
                });

            </script>
        </div>
        @section Scripts{
            <partial name="_ValidationScriptsPartial" />

            <script>
 $(function () {
                $('#btnUploadImage').on('click', function (evt) {
                    console.log("btnUploadImage");
                    evt.preventDefault();
                    console.log("btnUploadImage after evt.preventDefault()");
                    $.ajax({
                        url: '@Url.Page("", "OnPostUploadImage")',
                        //data: new FormData(document.forms[0]),
                        contentType: false,
                        processData: false,
                        type: 'post',
                        success: function () {
                            alert('Uploaded by jQuery');
                        }
                    });
                });
            });
            </script>
            }

.cs file CODE

public async Task<IActionResult> OnPost()
        {
            if (ModelState.IsValid)
            {
                return Page();
            }
            else
            {

                return Page();
            }
        }

        public IActionResult OnPostUploadImage()
        {

            //Some code here
        }

Upvotes: 0

Views: 1176

Answers (1)

LouraQ
LouraQ

Reputation: 6881

Verify that you add the following code to the ConfigureServices method of startup.cs:

 services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");

If you want to enter the OnPostUploadImage method, the url of the Ajax request needs to be changed to @Url.Page("", "UploadImage") without adding OnPost.

And the Ajax request should send the anti-forgery token in request header to the server.

Change your ajax as follow:

@section Scripts{
    <partial name="_ValidationScriptsPartial" />
    <script>
 $(function () {
                $('#btnUploadImage').on('click', function (evt) {
                    console.log("btnUploadImage");
                    evt.preventDefault();
                    console.log("btnUploadImage after evt.preventDefault()");
                    $.ajax({ 
                        url: '@Url.Page("", "UploadImage")',
                        //data: new FormData(document.forms[0]),
                        contentType: false,
                        processData: false,
                        beforeSend: function (xhr) {
                            xhr.setRequestHeader("XSRF-TOKEN",
                                $('input:hidden[name="__RequestVerificationToken"]').val());
                        },
                        type: 'post',
                        success: function () {
                            alert('Uploaded by jQuery');
                        }
                    });
                });
            });
    </script>
}

You can refer to this for more details.

Upvotes: 1

Related Questions