Pass paramater to webservice on ajax - c#

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 + '"}',

Related

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

passing string array from ajax to c# web method

Hi I have this code below
How could I pass preferably 1 array which will contain an ID number and a value from a textbox which is dynamically generated and then passed to the backend to C#
var listoftextboxesWithValues = new Array();
var listoftextboxesWithID = new Array();
var i = 0;
$.each(listOftxtPriceTypeID, function (index, value) {
listoftextboxesWithID[i] = value.ID.toString();
listoftextboxesWithValues[i] = $("#txtPriceTypeID" + value.ID).val().toString();
i++;
});
//---Till here the data in the above arrays is as expected, the problem starts below in the data :
$.ajax({
type: "POST",
url: "/MemberPages/AdminPages/AdminMainPage.aspx/StoreNewProduct",
data: "{subCategoryID : '" + parseInt(subcategoryID) + "',name: '" + name + "',description: '" + description + "',quantity: '" + parseInt(quantity) + "',supplier: '" + supplier + "',vatRate: '" + parseFloat(VatRate) + "',colorID: '" + parseInt(colorID) + "',brandID: '" + parseInt(brandID) + "',imagePath: '" + fileNameGUID + "',listOfTextBoxes: '" + JSON.stringify(listoftextboxesWithValues) + "',listOfTextBoxesValues: '" + JSON.stringify(listoftextboxesWithID) + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("oh yeh");
},
error: function (error) {
alert("An Error Occured");
}
});
[WebMethod]
public static void StoreNewProduct(int subCategoryID, string name, string description, int quantity,
string supplier, float vatRate, int colorID, int brandID, string imagePath, string[] listOfTextBoxesID, string[] listOfTextBoxesValues )
{
Product p = new Product();
ProductPriceType ppt = new ProductPriceType();
p.CategoryID = subCategoryID;
p.Name = name;
p.Description = description;
p.Quantity = quantity;
p.Supplier = supplier;
// p.VATRate = vatRate;
p.ColorID = colorID;
p.BrandID = brandID;
p.Image = imagePath;
//...
}
Any help would be much appreciated
if I will do it, my approach is to seperate those two,
create string array for texts
create string array for values
i believe that the number of values will be the same with texts since it is generated dynamically.
then pass those two string arrays in c# backend.
you can use json2.js is cool ,I used this
var valueObj = { field1: $("input[name=field1]").val(),
field2: $("input[name=field2]").val()}
and then I can parse with this:
JSON.stringify(valueObj)
in the ajax call you can use like this
$.ajax({
type: "POST",
url: "/MemberPages/AdminPages/AdminMainPage.aspx/StoreNewProduct",
data:valueObj ,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("oh yeh");
},
error: function (error) {
alert("An Error Occured");
}
});
//In JS file
var arr = [];
arr.push( $("#textZipcode").val());
arr.push( $("#textPhone").val());
arr.push($("#textAddress").val());
arr.push( $("#textMobile").val());
//You can add any number. It will store to array properly.
$.ajax({
type: "POST",
url: "HomePage.aspx/SaveData",
contentType: "application/json; charset=utf-8",
dataType: "json",
data:JSON.stringify({arr:arr}),
success: function (response) {
}});
//In C#
[WebMethod]
public static void SaveData(string[] arr)
{
}

how to pass a value as a parameter while calling a jquery function

function getReportGroups() {
$.ajax({
contentType: "application/json; charset=utf-8",
url: "ReportGroups.ashx",
data: {
'method': 'getReportGroups',
'projectId': '30390'
},
dataType: "json",
success: function (data) {
alert('inside success');
var i = 0;
groupName = [data[i].name];
while (data[i] != null) {
alert([data[i].name]);
alert([data[i].reportGroupId]);
$("#top-node").append("<li item-checked='true' item-expanded='true'><a href=# style=font-weight:bold>" + [data[i].name] + "</a>");
i++;
var id = [data[i].reportGroupId];
getReports(id);
}
},
error: function (result) {
alert("Error- Inside the error loop");
}
});
}
function getReports(id) {
$.ajax({
contentType: "application/json; charset=utf-8",
url: "ReportGroups.ashx",
data: {
'method': 'getReports',
'reportGroupId': id
},
dataType: "json",
success: function (data) {
alert('inside getReports success');
var i = 0;
groupName = [data[i].name];
while (data[i] != null) {
alert([data[i].name]);
i++;
}
},
error: function (result) {
alert("Error- Inside the error loop");
}
});
}
This is my code.
Here when i call the getReports(id) from the getReportGroups() with the parameter id, the id is passed as zero in the getReoprts() function. I don know whats the problem. i used an alert box to check whether the 'id' exist in the first one, it does.. I have a valid Id in the getReportsFunction. But i am getting the id as zero in the second. What am i doing wrong here ?
Problem looks like i++, you can use .each() to iterate through the data
$.each(data, function(idx, item){
alert(item.name);
alert([item.reportGroupId]);
$("#top-node").append("<li item-checked='true' item-expanded='true'><a href=# style=font-weight:bold>" + [item.name] + "</a>");
var id = [item.reportGroupId];
getReports(id);
})
Looks like you're incrementing i before calling var id = data[i].reportGroupId, where as you test the value on the first iteration (alert([data[i].reportGroupId]);).
Move i++ as the last statement of the while loop and see if this resolves your issue.

pass to javascript class object is serialized in code behind

JavaScriptSerializer jss = new JavaScriptSerializer();
var seferim = jss.Serialize(sefer);
string asds = seferim.ToString();
asds = HttpUtility.HtmlEncode(asds);
function otobusGetir(id, b, i) {
id = encodeURI(id);
$.ajax({
type: 'POST',
url: 'BiletSatis.aspx/Getir',
contentType: 'application/json;charset=utf-8',
dataType: 'json',
data: '{"id":"' + id + '","Binis":"' + b + '","Inis":"' + i + '"}',
success: function () { },
error: function () { }
})
[WebMethod]
public static string Getir(string id, string Binis, string Inis)
{
string a = id;
string b = HttpUtility.HtmlDecode(id);
return null;
}
The problem is javascript function cannot take parameter(Uncaught SyntaxError: Unexpected token ILLEGAL) which is serialized.How i can totally done tihs job?
The problem is that this is not working while javascript function run it can not take argument,how can totaly don this job
Try like this:
function otobusGetir(id, b, i) {
$.ajax({
type: 'POST',
url: 'BiletSatis.aspx/Getir',
contentType: 'application/json;charset=utf-8',
dataType: 'json',
data: JSON.stringify({ id: id, Binis: b, Inis: i }),
success: function () { },
error: function () { }
});
}
and to call the function:
otobusGetir(123, 'foo bar', 'baz');
and the page method:
[WebMethod]
public static string Getir(string id, string Binis, string Inis)
{
// don't use any Html decoding here. The parameters will
// already be properly formatted so you can use them directly
return null;
}

string does not pass to controller

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
...

Categories

Resources