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"]}:
Related
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.
Here is my controller. I am trying to pass the value through an if statement but it's not equalling (==) the string of "2019".
[HttpPost]
public ActionResult Extract(string[] response)
{
string statementQuery = "";
if (response!=null)
{
for (var i = 0; i < response.Length; i++)
{
if (response[i] == "2019")
{
statementQuery = "select statementPath from ClientStatements_Inventory where statementYear = '" + response[i] + "';";
}
}
}
Here is my ajax call. Is it something to do with the way it is sending to my controller? or my if statement?
$('#main-content-submit').click(function () {
var labelArray = [];
labelArray = $("input:checkbox:checked").map(function () {
return $(this).closest('label').text();
}).get();
console.log(labelArray);
event.preventDefault();
$.ajax({
type: 'POST',
url: '/Home/Extract',
data: JSON.stringify({ response:labelArray }),
contentType: 'application/json; charset=utf-8',
success: function (result) {
alert("Month and ear passed to controller");
},
error: function (err, result) {
alert("Error in Extract" + err.responseText);
},
});
return false;
});
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
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 };
i am trying to post my string called 'selected' trough my $.ajax call but the controller(selected=null) receives a null value? selected has a value ({'selected':0100}) according to fiddler?
[HttpPost]
public ActionResult Index(string selected)
{
return Json(new {value = "this is a test"});
}
$(document).ready(
$("#btnSave").click(
function () {
var checkboxesselected = "0100";
$.ajax({ type: 'POST',
url: "/Home/Index",
datatype: 'json',
data: "{'selected':" + checkboxesselected + "}"
});
}
)
The problem is you're sending the data to jQuery as a string literal as opposed to an object. Your line with the data parameters should be data: {selected: checkboxesselected }
You're missing the quotes around "checkboxesselected "
$(document).ready(
$("#btnSave").click(
function () {
var checkboxesselected = "0100";
$.ajax({ type: 'POST',
url: "/Home/Index",
datatype: 'json',
data: "{ 'selected' : '" + checkboxesselected + "'}"
});
}
)
try:
var val = { selected: checkboxesselected };
and then:
...
datatype: 'json',
data: val
...