[英]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.我有一个表单,其中有两个按钮,一个是使用 ajax 调用上传图像,其他是保存所有数据的主要提交按钮。
I am still very new to asp.net core and trying different thing to learn asp.net core with razor page.我对 asp.net 内核仍然很陌生,并尝试不同的东西来学习 asp.net 内核和 razor 页面。
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我的问题是,当我点击提交按钮时,它找不到处理程序方法,经过一整天的故障排除,没有任何效果,最后几篇文章指出错误/防伪失败,我不知道如何在下面的代码中实现它,因为我尝试了一些但他们给出的错误可能是旧引用核心 2.2 等示例 1 示例2的文章
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 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.我希望它在 pageModel 文件中调用
OnPostUploadImage
方法,但它总是使用默认OnPost
方法。 when i rename the OnPost
to OnPost2
nothing happend..当我将
OnPost2
重命名为OnPost
时,什么也没发生。
How can i call OnPostUploadImage()
on button btnUploadImage
click event.如何在按钮
btnUploadImage
单击事件上调用OnPostUploadImage()
。
When i hit click btnUploadImage
it generates following error on browser console当我点击
btnUploadImage
时,它会在浏览器控制台上生成以下错误
Error in FF FF 中的错误
XML Parsing Error: no root element found Location: https://localhost:44364/Admin/News/NewsCreate?handler=OnPostUploadImage Line Number 1, Column 1:
XML 解析错误:找不到根元素 位置: https://localhost:44364/Admin/News/NewsCreate?handler=OnPostUploadImage行号 1,第 1 列:
Error in Chrome Chrome 中的错误
jquery.min.js:2 POST https://localhost:44364/Admin/News/NewsCreateMultipleSubmit?handler=OnPostUpLoadImage 400 (Bad Request)
jquery.min.js:2 POST https://localhost:44364/Admin/News/NewsCreateMultipleSubmit?handler=OnPostUpLoadImage 400(错误请求)
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 .cs 文件代码
public async Task<IActionResult> OnPost()
{
if (ModelState.IsValid)
{
return Page();
}
else
{
return Page();
}
}
public IActionResult OnPostUploadImage()
{
//Some code here
}
Verify that you add the following code to the ConfigureServices
method of startup.cs:验证是否将以下代码添加到 startup.cs 的
ConfigureServices
方法中:
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.如果要进入
OnPostUploadImage
方法,需要将Ajax请求的url改为@Url.Page("", "UploadImage")
,不添加OnPost。
And the Ajax request should send the anti-forgery token
in request header to the server.并且 Ajax 请求应该将请求 header 中
anti-forgery token
发送到服务器。
Change your ajax as follow:更改您的 ajax 如下:
@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>
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.