Fully working example with (.Net Core). Some portion of the answer adopted from the above answers with fixing the compilation errors.
Assuming you want to upload files then you'll submit the form with the uploaded files.
Register.cshtml
@using UploadFileAjaxPostWebApp.Models.Account
@model RegisterModel
@using (Html.BeginForm("Register", "Account", FormMethod.Post))
{
<div>
<label>First Name </label>
<input type="text" name="FirstName" value="John" />
</div>
<div>
<label>Second Name </label>
<input type="text" name="SecondName" value="Smith" />
</div>
<div>
<label>Resume</label>
<input type="file" id="fileUpload1" onchange="uploadFiles('fileUpload1');" />
<input type="hidden" id="ResumeFileName" name="ResumeFileName" value="@Model.ResumeFileName" />
</div>
<div>
<input type="submit" value="Submit" />
</div>
}
<script type="text/javascript">
function uploadFiles(inputId) {
var input = document.getElementById(inputId);
var files = input.files;
var formData = new FormData();
for (var i = 0; i !== files.length; i++) {
formData.append("files", files[i]);
}
$.ajax(
{
url: "/account/uploadfiles",
data: formData,
processData: false,
contentType: false,
type: "POST",
success: function (data) {
// Set the property of the Model.
$("#ResumeFileName").val(data.fileName);
alert("Files Uploaded! " + data.fileName);
}
}
);
}
</script>
Account Controller:
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using UploadFileAjaxPostWebApp.Models.Account;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Net.Http.Headers;
namespace UploadFileAjaxPostWebApp.Controllers
{
public class AccountController : Controller
{
private readonly IWebHostEnvironment _hostEnvironment;
public AccountController(IWebHostEnvironment hostEnvironment)
{
_hostEnvironment = hostEnvironment;
}
public IActionResult Register()
{
RegisterModel model = new RegisterModel();
return View(model);
}
[HttpPost]
public IActionResult Register(RegisterModel model)
{
// Handle your post action ....
return View(model);
}
[HttpPost]
public async Task<ActionResult> UploadFiles(IList<IFormFile> files)
{
string fileName = null;
foreach (IFormFile source in files)
{
// Get original file name to get the extension from it.
string orgFileName = ContentDispositionHeaderValue.Parse(source.ContentDisposition).FileName.Value;
// Create a new file name to avoid existing files on the server with the same names.
fileName = DateTime.Now.ToFileTime() + Path.GetExtension(orgFileName);
string fullPath = GetFullPathOfFile(fileName);
// Create the directory.
Directory.CreateDirectory(Directory.GetParent(fullPath).FullName);
// Save the file to the server.
await using FileStream output = System.IO.File.Create(fullPath);
await source.CopyToAsync(output);
}
var response = new { FileName = fileName };
return Ok(response);
}
private string GetFullPathOfFile(string fileName)
{
return $"{_hostEnvironment.WebRootPath}\\uploads\\{fileName}";
}
}
}
RegisterModel class
namespace UploadFileAjaxPostWebApp.Models.Account
{
public class RegisterModel
{
public string FirstName { get; set; }
public string SecondName { get; set; }
public string ResumeFileName { get; set; }
}
}
data: {formData:formData}
? What isformData
expected to be atpublic async Task<JsonResult> UploadFile(IFormFile formData)
? What is purpose ofTask<JsonResult>
?