File upload in server using ajax - c#

I am working web form (.aspx) application.
I need to file upload in server using ajax
I can't send file.
any one help me(with details).
var files = $("#bodyContentPlaceHolder_fileProfilePhoto")[0].files[0];
$.ajax({
type: "POST",
url: "User.aspx/AjaxSaveUser",
//contentType: false,
data: JSON.stringify({ model: model, inputFile: files }),
dataType: "json",
contentType: "application/json; charset=utf-8",
processData: false,
success: function (data) {
AlertMessage(model.UserID, "success");
GridDataBind(data);
$('#myModal').modal('toggle');
},

Javascript client side code:
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"];

Related

Single parameter not being received in my web api 2.0 controller

Background:
I am trying to send a single string to a Webapi which resides with in the same MVC application. I am using a Kendo Datasource.
Issue:
Controller function in my Web api is being contacted by my data-source call, however the parameter is coming in as null.
Various JavaScript approaches taken :
var clientLookupDataSource = new kendo.data.DataSource({
serverFiltering: true,
transport: {
read: {
type: "POST",
url: siteRoot + "api/GetClientInfo",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: function (data) {
return JSON.stringify({ name: "Hello World"});
},
}
}
});
var clientLookupDataSource = new kendo.data.DataSource({
serverFiltering: true,
transport: {
read: {
type: "POST",
url: siteRoot + "api/GetClientInfo",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: function (data) {
return JSON.stringify("Hello World");
},
}
}
});
var clientLookupDataSource = new kendo.data.DataSource({
serverFiltering: true,
transport: {
read: {
type: "POST",
url: siteRoot + "api/GetClientInfo",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: function (data) {
return "Hello World";
},
}
}
});
C# WebApi 2.0 Controller
[HttpPost]
[Route("api/GetClientInfo")]
public IHttpActionResult SearchClients([FromBody]string name)
{
return Ok("Response to" + name);
}
Kendo Auto-Complete
$("#clientddl").kendoAutoComplete({
dataSource: clientLookupDataSource,
placeholder: "Type client name...",
filter: "contains",
dataTextField: "ClientName",
dataValueField: "ClientRef",
enabled: true,
minLength: 3,
delay: 350,
change: function (e) {
var item = this.dataItem(e.item);
if (item != null) {
JobData.ClientId = item.ClientID;
doClientChange(e);
}
}
});

How to send multiple data in single FormData object in Ajax?

My application has multiple data like Text-box value, label value, Drop-Down value,File Data and send same data at server side and store in database
To achieve this, i have used below method but now i want to use Formdata and append each value and send it to server side
How to achieve this scenario using Formdata with specific object type.
Below is the code
var selectedText = $('#Commentinput').text();
$('#actioncomments').text(selectedText);
var debitEntityValue = $('#DrAccount option:selected').text();
var creditEntityValue = $('#CrAccount option:selected').text();
var amount = $("#Amountinput").val();
var paymentActionReason = $('#action').text();
var paymentCommentReason = $('#Commentinput').val();
var prepayAccountId =#Model.prepaidBranchList.PrepaidID;
var transactionDate = '#DateTime.Today';
var transactionExtensions = "1";
var fileBase64Data = $("#fileUpload").text();
if ($('#Commentinput').val() == "") {
paymentCommentReason = "No Comment";
}
else {
paymentCommentReason = $('#Commentinput').val();
}
var adjustmentTransactioninfo =
{
PaymentReasonMasterId: paymentReasonMasterId,
DebitEntityValue: debitEntityValue,
CreditEntityValue: creditEntityValue,
Amount: amount,
PaymentActionReason: paymentActionReason,
PaymentCommentReason: paymentCommentReason,
PrepayAccountId: prepayAccountId,
TransactionDate: transactionDate,
TransactionExtensions: transactionExtensions
};
var data = JSON.stringify({
'adjustmentTransactioninfo': adjustmentTransactioninfo,
'fileData': 0
});
var url = "#Html.Raw(Url.Action("AdjustmentTransaction",
"PrepaidActivity"))";
url += '?branchCode=' + '#Model.prepaidBranchList.IASBranchCode'
$.ajax({
url: url,
traditional: true,
data: data,
enctype:"multipart/form-data",
contentType: "application/json charset=utf-8",
dataType: "json",
type: 'POST',
success: function (data) {
$("#ajaxLoader").show();
if (data != null) {
var ProductActionID = data.SuccessMessage.split(':');
uploadFile.append('ProductActionID' , ProductActionID[1]);
FileUpload(uploadFile);
var dialog = document.querySelector('#Finaldialog');
var ConfirmationScreen = $("<p></p>").text(data.SuccessMessage);
$("#finalmdl-dialog").append(ConfirmationScreen);
dialog.showModal();
dialog.querySelector('button:not([disabled])').addEventListener('click', function() {
dialog.close();
location.reload();
});
}
}
});`
Controller code
public JsonResult AdjustmentTransaction(TraxAdjustmentTransactionInfo adjustmentTransactioninfo, string fileData, string branchCode)
{
PrepaidAdminService.PrepaidAdminDashBoardServiceClient _PrepaidAdminService = new PrepaidAdminService.PrepaidAdminDashBoardServiceClient();
TraxAdjustmentTransactionResult result;
adjustmentTransactioninfo.ProductActionMasterId = Convert.ToInt16(System.Configuration.ConfigurationManager.AppSettings["ProductActionMasterId"]);
adjustmentTransactioninfo.ProductCode = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["ProductCode"]);
adjustmentTransactioninfo.DebitEntityMasterId = TraxEntityType.GPLedgerAccount;
adjustmentTransactioninfo.CreditEntityMasterId = TraxEntityType.GPLedgerAccount;
adjustmentTransactioninfo.UserId = Utility.UserID;
adjustmentTransactioninfo.RetailerId = _PrepaidAdminService.GetBranchRetailerId(branchCode);
use serializeArray and can be add the additional data:
var data = $('form').serializeArray();
data.push({name: 'Amit', value: 'love'});
$.ajax({
type: "POST",
url: "url",
data: data,
success: function(data) {
// do what ever you want with the server response
},
error: function() {
alert('error handing here');
}
});
Remove the #Html.Raw(Url.Action()), contentType and JSON.stringify() and leave that to the ModelBinder. Change your ajax to this:
$.ajax({
url: '#Url.Action("AdjustmentTransaction", "PrepaidActivity")',
traditional: true,
data: {
adjustmentTransactioninfo: adjustmentTransactioninfo,
fileData: "0",
branchCode: '#Model.prepaidBranchList.IASBranchCode'
},
enctype: "multipart/form-data",
type: 'POST',
success: function (data) {
alert("success");
}
});
var params = { param1: value, param2: value2}
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: '../aspxPage.aspx/methodName',
data: JSON.stringify(params),
datatype: 'json',
success: function (data) {
var MethodReturnValue = data.d
},
error: function (xmlhttprequest, textstatus, errorthrown) {
alert(" conection to the server failed ");
}
});
// Param1 and param2 name should be same as method argument

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"];

Unable to call aspx page web method using jquery ajax call?

Here is my ajax call
$(document).ready(function () {
$("#btnSubmit").click(function () {
alert("I am in ?");
$.ajax({
type: "POST",
url: "TestNew2.aspx/DisplayData",
data: "{}",
contentType: "application/x-www-form-urlencoded",
dataType: "text",
//success: function (msg) {
// // Replace the div's content with the page method's return.
// $("#btnSubmit").text(msg.d);
// alert(msg.d);
//}
success: function (result, status, xhr) {
document.getElementById("lblOutput").innerHTML = xhr.responseText
},
error: function (xhr, status, error) {
alert(xhr.error);
}
});
});
});
and my Web method[WebMethod]
public static string DisplayData()
{
return DateTime.Now.ToString();
}
Getting aspx page when trying to call web method on aspx page.Here is the jQuery code
Can any one point out what may be wrong.Because the web method is not getting called.
Try Like
$.ajax
({
url: " URL",
data: "{ 'name' : 'DATA'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
async: true,
dataFilter: function (data) { return data; },
success: function (data)
{
alert(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("error");
}
});
OR
jQuery.ajax({
type: "POST",
url: "Login.aspx/checkUserNameAvail",
contentType: "application/json; charset=utf-8",
data: "{'iuser':'" + userid + "'}",
dataType: "xml",
success: function (msg) {
$(msg).find("Table").each(function () {
var username = $(this).find('UserName').text();
if (username != '') {
//window.location.replace('/iCalendar.aspx');
alert('This username already taken..');
$("#reguser").val('');
$("#reguser").focus();
}
else {
}
});
},
error: function (d) {
}
});
.CS
[WebMethod(enableSession: true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Xml)]
public static string checkUserNameAvail(string iuser)
{
try
{
iCalendarClass iC = new iCalendarClass();
DataSet ds = iC.checkUserNameAvail(iuser);
return (ds.GetXml());
}
catch
{
return null;
}
}

Categories

Resources