How to send multiple data in single FormData object in Ajax? - c#

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

Related

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 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"]}:

Ajax webmethod, returning JSOn data

I am having some issues with a Webmethod (c#) populating a JQuery DataTable table with JSON data.
Ajax call:
function loadTable(message) {
$.ajax({
type: "POST",
url: "TestBed.aspx/ValueDateSummary",
cache: false,
data: JSON.stringify({ senderBIC: senderBIC }),
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
},
success: function (msg) {
var data = msg.d;
alert(data["counter"]);
alert(data);
alert(typeof msg);
var otable = $("#test").dataTable({
// "sAjaxDataProp": msg.d,
"aoColumns": [
{ "mDataProp": "counter" },
{ "mDataProp": "SessionID" },
{ "mDataProp": "MsgType" }
]
});
}
});
};
No errors, but the datatable is empty.
Here are the results of the alerts
alert(data["counter"]) = UNDEFINED
alert(data) = [{"counter":3,"SessionID":"1","MsgType":"103","ValueDate":"2007-08-01","Sender":"1"}, {"counter":7,"SessionID":"2","MsgType":"103","ValueDate":"2009-05-26","Sender":"2"}]
alert(typeof msg) = OBJECT
any ideas why my table is empty?
* EDIT *
THIS IS THE FINAL SUCCESS METHOD WHICH WORKED
success: function (msg) {
var data = JSON.parse(msg.d);
$("#test").dataTable({
"aaData": data,
"aoColumns": [{
"mDataProp": "counter"
}, {
"mDataProp": "SessionID"
}, {
"mDataProp": "MsgType"
}]
});
}
You are never settings the data of the oTable...
You have to give it an Array of Arrays (var object = [][]):
You can either do it as ajax and put your $ajax code into the fnServerData function
Or do the following: (taken from example from DataTables)
function loadTable(message) {
$.ajax({
type: "POST",
url: "TestBed.aspx/ValueDateSummary",
cache: false,
data: JSON.stringify({
senderBIC: senderBIC
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
},
success: function (msg) {
var data = [];
$.map(msg.d, function (item) {
{
var row = [];
row.push(
item.counter,
item.SessionID,
item.MsgType
//Commented out because you didn't include them in your aoColumns declaration, if you want them in the table to access later just make them non-visible.
//item.ValueDate,
//item.Sender
);
data.push(row);
}
});
var otable = $("#test").dataTable({
"aaData": data,
"aoColumns": [
{"mDataProp": "counter"},
{"mDataProp": "SessionID"},
{"mDataProp": "MsgType"}
]
});
}
});
}
As of jQuery DataTables 1.7.2 you can use array of objects as a data source but only with the ajax source (sAjaxSource) and it is slightly slower because it just manually copies it to an array or arrays.
Try changing your success function to the following:
var data = msg.d;
alert(data["counter"]);
alert(data);
alert(typeof msg);
var rows = [];
for (var i = 0; i < data.length; i++) {
rows.push([
data[i].counter,
data[i].SessionID,
data[i].MsgType,
data[i].ValueDate,
data[i].Sender
]);
}
var otable = $("#test").dataTable({
"aaData": rows
});

Pass paramater to webservice on ajax

I have a simple web service with one argument :
public static string LoadComboNews(string id)
{
string strJSON = "";
DataRowCollection people = Util.SelectData("Select * from News where person = "+ id +" Order by NewsId desc ");
if (people != null && people.Count > 0)
{
//temp = new MyTable[people.Count];
string[][] jagArray = new string[people.Count][];
for (int i = 0; i < people.Count; i++)
{
jagArray[i] = new string[] { people[i]["NewsID"].ToString(), people[i]["Title"].ToString() };
}
JavaScriptSerializer js = new JavaScriptSerializer();
strJSON = js.Serialize(jagArray);
}
return strJSON;
}
on javascript I am trying to call it with parameter :
jQuery.ajax({
type: "POST",
url: "webcenter.aspx/LoadComboNews",
data: "{'id':usrid}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// Replace the div's content with the page method's return.
combonews = eval(msg.d);
}
});
UPDATE:
usrid is dynamic
Am I doing something wrong here?
data you are sending is invalid "{'id':usrid}"
this not a valid json
probably what you wanna do is assuming usrid is a variable
"{\"id\":"+usrid+"}"
with it shoudnt you be executing this command
Select * from News where person = '"+ id +"' Order by NewsId desc
Considering id is a string
also try this
combonews = JSON.stringify(msg);
Add WebMethod to the method
[WebMethod]
public static string LoadComboNews(string id)
And try this format
$.ajax({
type: "POST",
url: "webcenter.aspx/LoadComboNews",
data: '{"id":"usrid"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// Replace the div's content with the page method's return.
alert(msg.d);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
alert(textStatus + " " + errorThrown);
}
});
Or
data: '{"id":"' + usrid + '"}',

Categories

Resources