File Upload Through JQuery AJAX In ASP.NET MVC - c#

I have a requirement of sending invitations to candidates where a user selects the excel file, transfers it from ajax to controller and validates its size, type etc. Then user clicks on Send Invite button and sends the email invites(having excel file). Please find the below code for reference:
<button type="button" id="bulkuploadButton">Bulk Email Upload</button>
<input type="file" id="ExcelFile" name="ExcelFile" style="display:none" onchange="UploadFile();" onselect="UploadFile();" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" />
Jquery:
function UploadFile() {
if (ValidateExcelFile()) {
var excelFile = document.getElementById('ExcelFile');
formData = new FormData();
if (excelFile.files.length > 0) {
for (var i = 0; i < excelFile.files.length; i++) {
formData.append('file-' + i, excelFile.files[i]);
}
}
$.ajax({
url: url here,
type: "POST",
dataType: 'json',
processData: false,
contentType: false,
data: formData,
success: function (data) {
// Further Processing
},
error: function (err) {
//Error
}
});
}
}
Controller:
[HttpPost]
public JsonResult MyController(HttpPostedFileBase excelFile)
{
if (Request.Files.Count > 0)
{
foreach (string file in Request.Files)
{
excelFile = Request.Files[file];
}
var result = //Call Model here for validation checks and return error msges
TempData["ExcelFile"] = excelFile; //Store in TempData for further processing
return Json(result);
}
return null;
}
The validations are done successfully, now its time to send invite to candidates as:
<button onclick="SendInvite">Send Invitations</button>
Jquery:
function SendInvite() {
//Check validations for other inputs on the page
//Get the excel file same as above
var excelFile = document.getElementById('ExcelFile');
formData = new FormData();
if (excelFile.files.length > 0) {
for (var i = 0; i < excelFile.files.length; i++) {
formData.append('file-' + i, excelFile.files[i]);
}
}
$.ajax({
type: "POST",
url: url here,
data: JSON.stringify({
myModel: myModel,
excelFile: formData
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
},
error: function (data) {
}
});
}
Controller:
public JsonResult MyController2(MyModel myModel, HttpPostedFileBase excelFile)
{
//I tried the same method to get the file but it didn't help me
if (Request.Files.Count > 0) //Here Request.Files.Count = 0, it should be = 1 instead
{
foreach (string file in Request.Files)
{
excelFile = Request.Files[file];
}
}
//I then tied to use TempData but it does not have the excel data
excelFile = TempData["ExcelFile"] as HttpPostedFileBase;
//Further processing
I am getting this error while fetching data from TempData. ContentLength is 0 and also the data attribute is null
The data in TempData should be something like this (where ContentLength !=0
and data attribute has some value):
Can anyone help me get the excel data in controller MyController2.

Change the function SendInvite() as:
function SendInvite() {
//Check validations for other inputs on the page
//Get the excel file same as above
var excelFile = document.getElementById('ExcelFile');
formData = new FormData();
formData.append("data", JSON.stringify(myModel));
for (var i = 0; i < excelFile.files.length; i++) {
var file = ExcelFile.files[i];
formData.append("excelFile", file);
}
$.ajax({
type: "POST",
url: url here,
data: formData,
contentType: "application/json; charset=utf-8",
dataType: "json",
contentType: false,
processData: false,
success: function (data) {
},
error: function (data) {
}
});
}
and in controller
public JsonResult MyController2(string data, HttpPostedFileBase[] excelFile)
{
MyModel myModel = JsonConvert.DeserializeObject<MyModel>(data);
if (Request.Files.Count > 0)
{
//Do data processing here
}
//Further processing
Check this link How to Pass Image File and Form Data From Ajax to MVC Controller

Related

jQuery ajax passing null to controller in ASP .NET MVC

I am trying to send stringified array from view with $.ajax but I am constantly getting null in controller.
This is controller function:
[HttpPost]
public void SaveColumnsToDb(string data)
{
var a = data;
}
Console outputs:
str: (2) ['SerialNumber', 'MeasurementUnit']
JSON str: ["SerialNumber","MeasurementUnit"]
Whole function:
$("#popup-saveBtn").click(function () {
var columns = [];
var parentElement = document.getElementById("tableColumns");
var childElements = parentElement.querySelectorAll("input[type=checkbox]");
// If checkbox is checked, push value to array
for (i = 0; i < childElements.length; i++) {
if (childElements[i].checked) {
columns.push(childElements[i].value);
}
}
/*var strColumns = columns.join(";");*/
console.log("str: ", columns);
console.log("JSON str: ", JSON.stringify(columns));
// Send data to AjaxSelectController
$.ajax({
url: '#Url.Action("SaveColumnsToDb", "AjaxSelect", new { area = string.Empty })',
type: 'POST',
data: JSON.stringify(columns),
dataType: 'json',
contentType: 'application/json; charset=utf-8'
});
});
as a matter of fact, since you are using contentType: 'application/json; charset=utf-8', you are trying to send a json inside of the request body, so use this syntax
[HttpPost]
public void SaveColumnsToDb([FromBody] string[] data)
Changed the parameter name.
When we use an ajax request then we have to pass value in data and In the URL part, we have to give only the action name and controller name.
[HttpPost]
public void SaveColumnsToDb(string dataResponse)
{
var a = dataResponse;
}
$("#popup-saveBtn").click(function () {
var columns = [];
var parentElement = document.getElementById("tableColumns");
var childElements = parentElement.querySelectorAll("input[type=checkbox]");
// If checkbox is checked, push value to array
for (i = 0; i < childElements.length; i++) {
if (childElements[i].checked) {
columns.push(childElements[i].value);
}
}
/*var strColumns = columns.join(";");*/
console.log("str: ", columns);
console.log("JSON str: ", JSON.stringify(columns));
// Send data to AjaxSelectController
$.ajax({
url: '#Url.Action("SaveColumnsToDb", "AjaxSelect")',
type: 'POST',
data: { dataResponse: JSON.stringify(columns)},
dataType: 'json',
contentType: 'application/json; charset=utf-8'
});
});
I managed to make it work.
Changed data property in $.ajax().
data: JSON.stringify({ data: strColumns })
I am sending only csv string, e.g. "abc;abc;abc"
Controller is same.

How to send data object which contain upload files and string to controller using ajax?

I am sending array of object which contain upload file data and some string values to my controller using ajax but it sending failed.
I also tried with formdata but no luck.I want to know how i send data to controller.
Jquery/View Code:
function SaveBrandDetail() {
debugger;
var data = new Array();
var tablecount = 0;
$(".DataRow").each(function () {
tablecount = tablecount + 1;
var row = {
"SaleStartDateString": $(this).find(".clsSaleStartDateForVal").val(),
"BrandDetailId": $(this).find(".clsBrandDetailId").val(),
"SaleExpiryDateString": $(this).find(".clsSaleEndDateForVal").val(),
"BrandId": $(this).find(".clsBrandId").val(),
"Amount": $(this).find(".clsAmount").val(),
"CategoryId": $(this).find(".clsSubCategoryId").val(),
"ParentCategoryId": $(this).find(".clsParentCategoryId").val(),
"fileUpload": $(this).find(".fileUploadData").get(0).files[0]
};
data.push(row);
});
$.ajax({
url: '#Url.Action("SaveData","Data")',
type: "POST",
dataType: 'json',
contentType: 'application/json;',
data: JSON.stringify(data),
success: function (msg) {
},
error: function () {
}
});
}
Controller File:
public ActionResult SaveData(List<Data> data)
{
bool saved = false;
}
i expect to recieve data with upload file in my controller.i have declared HttpPostedFileBase in my modal class.
var formData = new FormData();
$(".DataRow").each(function () {
tablecount = tablecount + 1;
var row = {
"SaleStartDateString": $(this).find(".clsSaleStartDateForVal").val(),
"BrandDetailId": $(this).find(".clsBrandDetailId").val(),
"SaleExpiryDateString": $(this).find(".clsSaleEndDateForVal").val(),
"BrandId": $(this).find(".clsBrandId").val(),
"Amount": $(this).find(".clsAmount").val(),
"CategoryId": $(this).find(".clsSubCategoryId").val(),
"ParentCategoryId": $(this).find(".clsParentCategoryId").val(),
"FileName": $(this).find(".fileUploadData").get(0).files[0].name
};
var file = $(this).find(".fileUploadData").get(0).files[0];
formData.append(file.name, file);
data.push(row);
});
formData.append("data", JSON.stringify(data));
$.ajax({
url: '#Url.Action("SaveData","Data")',
type: "POST",
dataType: 'json',
data: formdata,
processData: false,
contentType: false,
success: function (msg) {
},
error: function () {
}
});
public ActionResult SaveData(string data)
{
var files = Request.Files;
List<Data> d = JsonConvert.Deserialize<List<Data>>(data);
foreach(var item in d)
{
var file = files[item.FileName];
}
bool saved = false;
}

Multiple parameters on jquery ajax call asp.net

I am trying to pass two parameters on an ajax call. I already tried several ways suggested on StakeOverflow but none worked. Here is my method signature on controller:
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase[] files, string[] usersToShare)
Here is my function:
function uploadFile() {
var formData = new FormData();
var totalFiles = document.getElementById("files").files.length;
for (var i = 0; i < totalFiles; i++) {
var file = document.getElementById("files").files[i];
formData.append("files", file);
}
//get the selected usernames (email) to share the file
var selectedUsers = [];
$("#costumerUsersListSelect :selected").each(function () {
selectedUsers.push($(this).val());
});
$.ajax({
type: 'post',
url: '/ManageFiles/UploadFile',
data: "files=" + formData + "usersToShare=" + selectedUsers,
dataType: 'json',
contentType: false,
processData: false,
success: function (data) {
},
error: function (error) {
}
});
}
So I want to pass to the controller the formData and the selectedUsers. If I pass just the formData (Data: formData) everything works but I need to pass the selectedUsers too.
Here what I already tried without any success:
data: JSON.stringify({ files: formData, usersToShare: selectedUsers }),
data: { files: formData, usersToShare: JSON.stringify(selectedUsers)},
data: "files=" + formData + "&usersToShare=" + selectedUsers,
data: "files=" + formData + "usersToShare=" + selectedUsers,
I am not sure if this is a syntax issue.
Thanks in advance for any help.
Instead of:
data: "files=" + formData + "usersToShare=" + selectedUsers,
append the selectedUsers in formData and send only formData to the server like:
data: formData,
and try again.
You need to use different keys for each value you append to formData, and then just append both files and users the same way
function uploadFile() {
var formData = new FormData();
var allFiles = $("#files").get(0).files;
for (var i = 0; i < allFiles.length; i++) {
formData.append("files_" + i, allFiles[i]);
}
$("#costumerUsersListSelect :selected").each(function(_,i) {
formData.append('user_' + i, this.value);
});
$.ajax({
type: 'post',
url: '/ManageFiles/UploadFile',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function(data) {},
error: function(error) {}
});
}
in your ajax:
data: JSON.stringify(obj);
before your ajax statement, define your parameters like:
var obj = { files: formData , usersToShare: selectedUsers };

JQuery Ajax uploading a file and other values from client side [duplicate]

This question already has answers here:
How to append whole set of model to formdata and obtain it in MVC
(4 answers)
Closed 6 years ago.
I need to upload a file to the server and send a GUID value, both needed to complete an operation.
Is it possible to send both with one $.ajax statement?
Here's a snippet of the Upload action method I'm using
[HttpPost]
public ActionResult Upload()
{
HttpPostedFileBase file = Request.Files[0];
}
and here's a snippet of the Javascript code I'm using to send the file to the server
function upload() {
var formData = new FormData();
var totalFiles = document.getElementById("FileUpload").files.length;
for (var i = 0; i < totalFiles; i++) {
var file = document.getElementById("FileUpload").files[i];
formData.append("FileUpload", file);
}
$.ajax({
type: 'post',
url: '/myController/Upload',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function (response) {
alert('succes!!');
},
error: function (error) {
alert("errror");
}
});
}
This code is working well. The file is uploaded as expected but now I need to send a GUID to the same controller (Upload) so I wonder if I can send the GUID with the file in the same $.ajax statement?
function upload() {
var formData = new FormData();
var totalFiles = document.getElementById("FileUpload").files.length;
for (var i = 0; i < totalFiles; i++) {
var file = document.getElementById("FileUpload").files[i];
formData.append("FileUpload", file);
formData.append("guid", theGuid);
}
$.ajax({
type: 'post',
url: '/myController/Upload',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function (response) {
alert('succes!!');
},
error: function (error) {
alert("errror");
}
});
}
on server side:
Request.Form["guid"];
Request.Files["FileUpload"];

JQuery Ajax to send Sortable Array in C#

I'm picking up items from a ul, and turning into an array. My controller is below and the variable items is getting empty​​.
What should I do to the controller receiving the correct value.
Controller:
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GravarConfiguracao(string[] itens)
{
var indicaores = itens;
var sequencia = 1;
foreach (var item in indicaores)
{
var atualizaIndicador = IndicadoresDoUsuario.AtualizarSequencia(Usuario.Codigo, Convert.ToInt32(item), sequencia);
sequencia++;
}
return Json(new { HttpStatusCode.OK });
}
JQuery:
$.ajax({
type: 'GET',
url: makeUrl("Indicador/GravarConfiguracao"),
data: JSON.stringify({ itens: $("#sort1").sortable('toArray') }),
dataType: 'json',
contentType: 'application/json',
success: function (dados) {
},
error: function (err) {
alert("Erro: - " + err);
}
});
JQuery send:
Query String Parameters:
{"itens":["itemIndicador_3","itemIndicador_10","itemIndicador_11"]}:

Categories

Resources