javascript 在 ASP.Net Core MVC 中使用 AJAX 提交表单
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51621103/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Submit a Form using AJAX in ASP.Net Core MVC
提问by Praveen Rai
I am working with ASP.Net Core 2.1, and trying to upload a file while returning it's url, without refreshing the page.
我正在使用 ASP.Net Core 2.1,并尝试在返回它的 url 的同时上传文件,而不刷新页面。
I am trying to write the JavaScript in site.js as the _RenderPartial("scripts") renders all scripts at the end of the page and hence directly using script tag in the razor view is not working. Secondly, adding it to site.js gives me an opportunity to call the script across the site views.
我正在尝试在 site.js 中编写 JavaScript,因为 _RenderPartial("scripts") 在页面末尾呈现所有脚本,因此在 razor 视图中直接使用脚本标记不起作用。其次,将它添加到 site.js 使我有机会跨站点视图调用脚本。
My Controller action looks like :
我的控制器操作如下所示:
[HttpPost]
[DisableRequestSizeLimit]
public async Task<IActionResult> Upload()
{
// Read & copy to stream the content of MultiPart-Form
// Return the URL of the uploaded file
return Content(FileName);
}
My view looks like :
我的观点如下:
<form id="FileUploadForm" action="~/Resources/Upload" method="post" enctype="multipart/form-data">
<input name="uploadfile" type="file" />
<button name="uploadbtn" type="submit" onclick="SubmitForm(this.parentElement, event)">Upload</button>
The site.js currently looks like :
site.js 目前看起来像:
function SubmitForm(form, caller) {
caller.preventDefault();
$.ajax(
{
type: form.method,
url: form.action,
data: form.serialize(),
success: function (data) { alert(data); },
error: function (data) { alert(data); }
})}
Presently, the code bypasses the entire script and the file is uploaded and new view displaying the file name is returned. I need help to create the javascript.
目前,该代码绕过整个脚本并上传文件并返回显示文件名的新视图。我需要帮助来创建 javascript。
回答by Shyju
Unfortunately the jQuery serialize()method will not include input file elements. So the file user selected is not going to be included in the serialized value (which is basically a string).
不幸的是,jQueryserialize()方法将不包括输入文件元素。所以用户选择的文件不会包含在序列化值(基本上是一个字符串)中。
What you may do is, create a FormDataobject, append the file(s) to that. When making the
ajax call, you need to specify processDataand contentTypeproperty values to false
您可以做的是,创建一个FormData对象,将文件附加到该对象。进行ajax调用时,需要指定processData和contentType属性值false
<form id="FileUploadForm" asp-action="Upload" asp-controller="Home"
method="post" enctype="multipart/form-data">
<input id="uploadfile" type="file" />
<button name="uploadbtn" type="submit">Upload</button>
</form>
and here in the unobutrusive way to handle the form submit event where we will stop the regular behavior and do an ajax submit instead.
在这里以一种不显眼的方式来处理表单提交事件,我们将停止常规行为并改为执行 ajax 提交。
$(function () {
$("#FileUploadForm").submit(function (e) {
e.preventDefault();
console.log('Doing ajax submit');
var formAction = $(this).attr("action");
var fdata = new FormData();
var fileInput = $('#uploadfile')[0];
var file = fileInput.files[0];
fdata.append("file", file);
$.ajax({
type: 'post',
url: formAction,
data: fdata,
processData: false,
contentType: false
}).done(function (result) {
// do something with the result now
console.log(result);
if (result.status === "success") {
alert(result.url);
} else {
alert(result.message);
}
});
});
})
Assuming your server side method has a parameter of with name same as the one we used when we created the FormDataobject entry(file). Here is a sample where it will upload the image to the uploadsdirectory inside wwwwroot.
假设您的服务器端方法有一个名称与我们在创建FormData对象 entry( file)时使用的名称相同的参数。下面是一个示例,其中将图像上传到uploads目录中wwwwroot。
The action method returns a JSON object with a status and url/message property and you can use that in the success/donehandler of the ajax call to whatever you want to do.
action 方法返回一个带有状态和 url/message 属性的 JSON 对象,你可以在 ajax 调用的success/done处理程序中使用它来执行任何你想做的事情。
public class HomeController : Controller
{
private readonly IHostingEnvironment hostingEnvironment;
public HomeController(IHostingEnvironment environment)
{
_context = context;
hostingEnvironment = environment;
}
[HttpPost]
public async Task<IActionResult> Upload(IFormFile file)
{
try
{
var uniqueFileName = GetUniqueFileName(file.FileName);
var uploads = Path.Combine(hostingEnvironment.WebRootPath, "uploads");
var filePath = Path.Combine(uploads, uniqueFileName);
file.CopyTo(new FileStream(filePath, FileMode.Create));
var url = Url.Content("~/uploads/" + uniqueFileName);
return Json(new { status = "success", url = url });
}
catch(Exception ex)
{
// to do : log error
return Json(new { status = "error", message = ex.Message });
}
}
private string GetUniqueFileName(string fileName)
{
fileName = Path.GetFileName(fileName);
return Path.GetFileNameWithoutExtension(fileName)
+ "_"
+ Guid.NewGuid().ToString().Substring(0, 4)
+ Path.GetExtension(fileName);
}
}
回答by Praveen Rai
Sharing the code that worked for me, implementing @Shyju's answer.
分享对我有用的代码,实现@Shyju 的回答。
View ( Razor Page ):
查看(剃刀页面):
<form name="UploadForm" action="~/Resources/Upload" method="post" enctype="multipart/form-data">
<input name="uploadfile" type="file" />
<button name="uploadbtn" type="submit" onclick="SubmitForm(this.parentElement, event)">Upload</button>
AJAX code added in Site.js (to make it a reusable):
Site.js 中添加的 AJAX 代码(使其可重用):
// The function takes Form and the event object as parameter
function SubmitForm(frm, caller) {
caller.preventDefault();
var fdata = new FormData();
var file = $(frm).find('input:file[name="uploadfile"]')[0].files[0];
fdata.append("file", file);
$.ajax(
{
type: frm.method,
url: frm.action,
data: fdata,
processData: false,
contentType: false,
success: function (data) {
alert(data);
},
error: function (data) {
alert(data);
}
})
};
};

