How to add property to a file when sending it over AJAX? - javascript

I have an MVC application where I am uploading picture files in an application.
The code for this:
var files = $(".uploadFile").data("files");
$.each(files, function (key, value) {
data.append('file', value);
})
$('.userForm *').filter(':input').each(function (index, value) {
data.append(value.id, $("#" + value.id).val());
});
$.ajax({
url: "/Customer/AddCustomer",
type: 'POST',
data: data,
cache: false,
processData: false,
contentType: false,
success: function (data) {
// logic
$.LoadingOverlay("hide");
},
error: function (event, jqxhr, settings, thrownError) {
// logic
$.LoadingOverlay("hide");
}
});
Server code:
public string AddCustomer(HttpPostedFileBase file, Customer customer)
{
// add customer and return to edit view
return partialView("customerEdit");
}
I am trying to figure out how i can add a property to each file that I send?
for example for every file that i add I create a list which I append to the DOM.
In this list there is a checkbox next to each file which indicates if this file(picture) should be the profile picture or not.
How do I append a boelan property to each file?

Thanks to #adeneo my brain got a jump start.
I had to retrhink my strategy here since I did not want to send the extra paramaters as a concatinated string.
I did the following:
In my first post I sent the file and the customer data. I saved the customer in the DB and for the file i stored it in tempdata in order to be able to access it in my second post where i would be savinng the file to the db with desiered extra paramaters.
script:
$.ajax({
url: "/Customer/AddCustomer",
type: 'POST',
data: data,
cache: false,
processData: false,
contentType: false,
success: function (data) {
// "Pictures" is an array that contains objects with all the file names and other properties.
$.ajax({
url: "/Customer/AddCustomerPictures",
type: 'POST',
data: JSON.stringify({ pictureFiles: Pictures}),
contentType: 'application/json; charset=utf-8',
success: function(data) {
//logic
}
});
//logic
},
error: function (event, jqxhr, settings, thrownError) {
//logic
}
});
server code, NOTE entire soloution not included:
public ActionResult AddCustomer(CustomerM customer)
{
var Id = _iScissorFingersManager.AddCustomer(customer.FirstName, customer.LastName, customer.Email,customer.PhoenNumber);
if (Request.Files.Count != 0)
{
TempData["files"] = Request.Files;
TempData["Id"] = Id;
}
// add customer and return to edit view
return PartialView("CustomerEdit", customer);
}
public ActionResult AddCustomerPictures(List<PictureFiles> pictureFiles)
{
var files = (HttpFileCollectionBase)TempData["files"];
var id = (long) TempData["Id"];
if (files != null)
{
foreach (var p in pictureFiles)
{
for (int i = 0; i < files.Count; i++)
{
HttpPostedFileBase hpf = files[i];
p.Name == files[i].FileName && p.IsProfile ? _iScissorFingersManager.UploadCustomerPictures(hpf.InputStream, hpf.ContentType, id, true), _iScissorFingersManager.UploadCustomerPictures(hpf.InputStream, hpf.ContentType, id);
}
}
}
return PartialView("CustomerProfileImage");
}

Related

how to append model object to formData in AJAX and retrieve using asp.net

I developed an Ajax POST method to pass the data to the controller. First I append my uploaded file to formData. Then I want to bind a model object to it. I did it. But in the controller, my model is always null.
Please help me how to append correctly and get the model and file correctly
javascript function:
var $file = document.getElementById('file'),
$formData = new FormData();
if ($file.files.length > 0) {
for (var i = 0; i < $file.files.length; i++) {
$formData.append('file-' + i, $file.files[i]);
}
}
var SnapShotReceivedData = [{
REASON: REASON_EXEMPT,
COMMENT: COMMENT_EXEMPT,
ATTACHMENT: $formData
}];
SnapShotReceivedData = JSON.stringify({ 'SnapShotReceivedData': SnapShotReceivedData})
$formData.append('SnapShotReceivedData',SnapShotReceivedData);
$.ajax({
contentType: false;
processData: false,
type: 'POST',
url: '#Url.Action("SetHCMNIDSnapData", "Home")',
data: $formData ,
success: function (result) {
},
failure: function (response) {
// $('#result').html(response);
}
});
Controller:
public JsonResult SetHCMNIDSnapData(List<SnapShot> SnapShotReceivedData)
{
if (Request.Files.Count > 0)
{
foreach (string file in Request.Files)
{
var _file = Request.Files[file];
}
}
}
my model is SnapShotReceivedData.When I debug the controller, the model object always null. please help me to solve this.

How to pass multiple file names from input type file to a web method

Hi ihave this input with type file with multiple select enabled.
i need to get the files from the file input and pass it to my webmethod but i'm getting none in my webmethod, i've read that prop return a list, i have this code in jquery
function post_RepAttach(){
var params = {
Ocap_no:$('#txtOcapNo').val(),
file_Name:$('#FileUpload1').prop("files")[0]
}
var files = $('#FileUpload1').prop("files")[0];
alert(files);
$.ajax({
type: 'POST',
contentType: 'application/json',
url: baseUrl + 'Create-OCAP.aspx/post_attachment_rep',
data: JSON.stringify(params),
dataType: 'json',
success: function (data) {
var response = data;
if (typeof callback != 'undefined') {
//hideLoadingGif();
//callback(response);
}
},
error: function (xhr, status, error) {
//hideLoadingGif();
console.log(xhr, status, error);
}
});
}
i have try this $('#FileUpload1').prop("files") remove the [0] but still no luck
and here's my webMethod
[WebMethod]
public static string post_attachment_rep(string Ocap_no, List<string> file_Name)
{
OcapDataAccess ODA = new OcapDataAccess();
bool result;
result = ODA.insert_reports(HttpContext.Current.Request.MapPath("~/OCAP/files/Reports/" + file_Name.ToString()), Ocap_no);
if (result == true)
{
return "1";
}
else
{
return "0";
}
}
but the file_Name count is zero even if i selected files
how can i achive it.
Hope you understand what i mean
var fileNames = $.map( $('#FileUpload1').prop("files"), function(val) { return val.name; });
and params is :
var params = {
Ocap_no:$('#txtOcapNo').val(),
file_Name:fileNames }
}

Passing A Single Objects Into An MVC Controller Method Using jQuery Ajax

I'm trying to post a single object data to an MVC Controler using JQuery, Below are my codes.
//declare of type Object of GroupData
var GroupData = {};
//pass each data into the object
GroupData.groupName = $('#groupName').val();
GroupData.narration = $('#narration').val();
GroupData.investmentCode = $('#investmentCode').val();
GroupData.isNew = isNewItem;
//send to server
$.ajax({
url: "/Admin/SaveContributionInvestGroup",
type: "POST",
contentType: "application/json;charset=utf-8",
dataType: "json",
data: JSON.stringify({ GroupData: JSON.stringify(GroupData) }),
success: function (res) {
alertSuccess("Success", res.Message);
//hide modal
$('#product-options').modal('hide');
hide_waiting();
},
error: function (res) {
alertError("Error", res.Message);
}
});
Below is my controller.
[HttpPost]
public JsonResult SaveContributionInvestGroup(ContributionInvestmentGroup GroupData)
{
ClsResponse response = new ClsResponse();
ClsContributionInvestmentGroup clsClsContributionInvestmentGroup = new ClsContributionInvestmentGroup();
var userID = (int)Session["userID"];
var sessionID = (Session["sessionID"]).ToString();
if (contributionGroupData != null)
{
//get the data from the cient that was passed
ContributionInvestmentGroup objData = new ContributionInvestmentGroup()
{
contributionInvestmentGroupID = 0,
groupName = GroupData.groupName,
narration = GroupData.narration,
investmentCode = GroupData.investmentCode,
isNew = GroupData.isNew
};
response = clsClsContributionInvestmentGroup.initiateNewContributionInvestmentGroup(sessionID, objData);
}
else
{
response.IsException = true;
response.IsSucess = false;
response.Message = "A system exception occurred kindly contact your Administrator.";
}
return Json(new
{
response.IsSucess,
response.Message
});
}
The issue is, the data is not been posted to the controller, the controller receives a null object.
Kindly assist, would really appreciate your effort, thanks.
Try Like this:
//send to server
$.ajax({
type: "POST",
url: "/Admin/SaveContributionInvestGroup",
dataType: "json",
data: GroupData,
success: function (res) {
alertSuccess("Success", res.Message);
//hide modal
$('#product-options').modal('hide');
hide_waiting();
},
error: function (res) {
alertError("Error", res.Message);
}
});
in your controller your dont have custom binding to bind JSON to your model thats why you get null in you parameter.
instead just post it as query, try simply changes your ajax option like so:
{
...
contentType: "application/x-www-form-urlencoded", //default:
...,
data: $.param(GroupData),
...
}
and perhaps property names are case sensitive so you will need to change your javascript model's name

Pass an array as parameter to a controller from an ajax call in JavaScript

I'm working on an ASP.NET MVC 4 website and I've got some troubles with a functionality. I explain, I've to select entities displayed in a table with their linked checkbox :
Screenshot of my table where each row has a checkbox with the same Id as the entity
Console showing updates in the array
Inside my script I have been abled to store each checked Id's checkbox in an array and remove those if the checkbox is unchecked. But I can't pass the array to my controller's function to delete each selected entity in the database.
I used $.ajax() from jquery to send through a POST request the array (as JSON) but I always get 500 error :
JSON primitive invalid
Null reference
Here's my function in my script (I don't know if my array's format is valid) :
var sendDocsToDelete = function (docsArray) {
$.ajax({
type: 'POST',
url: 'Main/DeleteDocuments',
data: JSON.stringify(docsArray),
contentType: 'application/json; charset=utf-8',
datatype: 'json',
success: function (result) {
alert('Success ' + result.d);
},
error: function (result) {
alert('Fail ' + result.d);
}
});
}
Then, the POST call the following function in my controller :
[Authorize]
[WebMethod]
public void DeleteDocuments(string docsToDelete)
{
int id;
string[] arrayDocs = JsonConvert.DeserializeObject<string[]>(docsToDelete);
foreach (string docId in arrayDocs)
{
int.TryParse(docId, out id);
dal.DeleteDocument(id); // dal = DataAccessLayer is the class which interacts with the database by executing queries (select, delete, update...)
}
}
Update 2
[Authorize]
public ActionResult DeleteDocuments(int[] docsToDelete)
{
try{
foreach (string docId in arrayDocs)
{
int.TryParse(docId, out id);
dal.DeleteDocument(id); // dal = DataAccessLayer is the class which interacts with the database by executing queries (select, delete, update...)
}
return Json("Success");
}
catch
{
return Json("Error");
}
}
var sendDocsToDelete = function (docsArray) {
$.ajax({
type: 'POST',
url: 'Main/DeleteDocuments',
data: docsArray,
contentType: 'application/json; charset=utf-8',
datatype: 'json',
success: function (result) {
alert('Success ' + result.d);
},
error: function (result) {
alert('Fail ' + result.d);
}
});
}
Any ideas about this issue ? I hoped I was clear enough. Do not hesitate if you need more details.
If you are passing an integer array properly from $.ajax (i.e. your docsArray should be having value like [15,18,25,30,42,49]) then you should try :
[Authorize]
public ActionResult DeleteDocuments(int[] docsArray)
{
//int id;
//string[] arrayDocs = JsonConvert.DeserializeObject<string[]>(docsToDelete);
try {
foreach (int docId in docsArray)
{
//int.TryParse(docId, out id);
dal.DeleteDocument(docId); // dal = DataAccessLayer is the class which interacts with the database by executing queries (select, delete, update...)
}
return "Success ";
}
catch {
return "Error";
}
}
Update :
Your javascript code should be :
var sendDocsToDelete = function (docsArray) {
$.ajax({
type: 'POST',
url: 'Main/DeleteDocuments',
data: JSON.stringify(docsArray),
contentType: 'application/json; charset=utf-8',
datatype: 'json',
success: function (result) {
alert('Success ');
},
error: function (result) {
alert('Fail ');
}
});
}
Maybe the datatype in the JSON array is not a string? (This could happen if you have an array in the form of [45,64,34,6], or a mixed one like [345,"wef4"]).
To make sure something is a string in Javascript you can do this: var string = "".concat(otherVar);
Try changing your ajax data to something like this..
data : JSON.stringify({'docsToDelete':docsArray}),
Make these changes to your code.
In Jquery
data: docsArray, no need to stringify the array
In Controller
[Authorize] //remove [WebMethod]
public ActionResult DeleteDocuments(string[] docsToDelete) //Add ActionResult, Change parameter to accept array
{
int id;
string[] arrayDocs = docsToDelete; //no need of deserilization
foreach (string docId in arrayDocs)
{
int.TryParse(docId, out id);
dal.DeleteDocument(id); // dal = DataAccessLayer is the class which interacts with the database by executing queries (select, delete, update...)
}
return Json(id); //return id back to ajax call...
}

javascript ajax call not not hitting controller

I am trying to build up a list of mock files for Dropzone.js to consume. I have an MVC controller method defined as follows:
[HttpPost]
public async Task<JsonResult> GetImageInfo(int imageId)
{
//int imgId;
//int.TryParse(imageId, out imgId);
var image = await RepublikDb.PropertyImage.FindAsync(imageId);
var path = Server.MapPath(image.ImageURI);
var size = new FileInfo(path).Length;
var fileName = new FileInfo(path).Name;
var thumbnailURI = image.ThumbnailImage.ImageURI.TrimStart('~');
return Json(new { fileName = fileName, size = size, thumbnailURI = thumbnailURI });
}
I have tested this endpoint with Postman, and everything works as expected, however each time I try and get the data in JS, the server returns a 500 error code, with complaints of the following: Exception Details: System.ArgumentException: The parameters dictionary contains a null entry for parameter 'imageId' of non-nullable type 'System.Int32'
Here is the JS AJAX code:
//Entry point to JS from razor. A comma separated string is passed here. Eg. imageIds = "10,12,14,16"
EditFormInit("#Model.PropertyImageIds")
var EditFormInit = function (imageIds) {
var imageIdsArr = imageIds.split(",");
var imageFiles = [];
imageIdsArr.forEach(function (ImageId) {
var requestData = { imageId: parseInt(ImageId) };
//var reqUrl = "?imageId=";
//reqUrl = reqUrl.concat(requestData.imageId.toString());
$.ajax({
type: "POST",
url: "/Admin/PropertyImage/GetImageInfo",
data: requestData,
contentType: "text/json; charset=utf-8",
dataType: "json",
success: function (data, status, jqXHR) {
var image = { fileName: data.fileName, size: data.size, thumbnail: data.thumbnailURI }
imageFiles.push(image);
}
});
});
Try:
contentType: "application/json"
This should work
so i finally realised why the controller was not getting hit, and resolved that issue. The $.ajax was passing the controller a JSON request, which was obviously failing.Once I removed the offending lines, the controller breakpoint finally got hit.
$.ajax({
type: "POST",
url: "/Admin/PropertyImage/GetImageInfo",
data: requestData,
success: function (data, status, jqXHR) {
var image = { fileName: data.fileName, size: data.size, thumbnail: data.thumbnailURI }
imageFiles.push(image);
}}
);
Even though the response from the controller is now coming back, the imageFiles array is still null. What am I doing wrong here?

Categories