passing string array from ajax to c# web method - c#

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)
{
}

Related

Ajax and ASP.NET full string not being sent properly

I have an ajax call like so:
$.ajax({
type: "GET",
url: "/api/connection/NotifiyNextDepartment?questionId="
+ highestValue + "&department=" + jobTitle + "&customerId=" + customerID + "&jobNumber="
+ $("#communtiyDropdown").val() + $("#lotDropdown").val(),
dataType: "json",
cache: false,
success: function (data) {}
});
alert('Success, you\'re data has been saved!');
holder = [];
},
failure: function (errMsg) {
alert('Failed, somthing went wrong, please try again!');
}
jobTitle is equal to "Human Resources & Customer Experience Manager"
when I send it to .NET I only get this back:
public bool NotifiyNextDepartment(int questionid, string department, int customerId, string jobNumber)
{
}
Here department is equal to "Human Resources "
Why is .NET removing everything after the & and how do I fix this?
I think you should call encodeURIComponent on your parameters.
url: "/api/connection/NotifiyNextDepartment?questionId="
+ encodeURIComponent(highestValue) + "&department=" + encodeURIComponent(jobTitle) + "&customerId=" + encodeURIComponent(customerID) + "&jobNumber="
+ encodeURIComponent($("#communtiyDropdown").val() + $("#lotDropdown").val()),

Populate items in dropdownlist

I have one function in my code behind
[System.Web.Services.WebMethod]
public static pcpName[] getPcpNames(string pcpCounty, string claimType)
{
List<pcpName> pcpNames = new List<pcpName>();
string query = "SELECT DISTINCT [PCP_ID], [PCP_NAME]+':'+[PCP_ID] AS [PCP_NAME] FROM [dbo].[FreedomTrinity] WHERE [PCP_COUNTY] = '" + pcpCounty + "' AND [CLAIM_TYPE] = '" + claimType + "'";
SqlDataReader reader = Database.SQLRead(query);
while (reader.Read())
{
pcpName names = new pcpName();
names.PCP_ID = reader.GetString(0);
names.PCP_NAME = reader.GetString(1);
pcpNames.Add(names);
}
return pcpNames.ToArray();
}
Now I want to populate items in a drop down list using this out put using jQuery.
So I write the code like this in my js file.
$(document).ready(function () {
$("#drpPcpCounty").change(function () {
//Remove items from drpPcpName
$("#drpPcpName option").remove();
$.ajax({
type: "POST",
url: "FreedomContestation.aspx/getPcpNames",
data: '{pcpCounty: "' + $("#drpPcpCounty").val() + '", claimType: "' + $("input:radio[name='rbtnlstClaimType']:checked").val() + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
response($.map(data.d, function (item) {
for (i in data) {
var d = data[i];
$('#drpPcpName').append($("<option></option>").attr("value", d.PCP_ID).text(d.PCP_NAME));
}
}))
},
failure: function (response) {
alert(response.d);
}
});
});
});
But nothing is happening in dropdown list. Code behind code is returning the array with values. What to do after success: ??
EDIT 1
I track the code till response($.map(data.d, function (item) { . But I don't know what's happening inside it. No alert() working inside response($.map(data.d, function (item) {
Try this:
success: function (data) {
for (var i = 0;i < data.d.length;i++) {
var d = data.d[i];
$('#drpPcpName').append($("<option></option>").attr("value", d.PCP_ID).text(d.PCP_NAME));
}
},

How to use ScriptManager.RegisterStartupScript in a WebMethod in asp.net?

I have a condition where i need to call a jquery function using a webmethod as below:
[WebMethod]
public static void BindData(String Site)
{
String HTML = "";
Int32 i = 1;
DataTable dt = new DataTable();
dt = obj.GetAll(objprop);
if (dt.Rows[0]["UserId"].ToString() != "0")
{
foreach (DataRow item in dt.Rows)
{
string Email = Bal.Common.Decryptdata(item["Email"].ToString());
string SentInvitation = item["SentInvitation"].ToString();
SentInvitation = SentInvitation.ToString() == "1" ? "Already Invited" : "";
if (i % 2 == 0)
HTML += "<div class=~other_wish_row2~><div class=~friend_list_box1~><input type=~checkbox~ class=~chkEmail~ id=~chkId^" + i + "~/></div><div class=~friend_list_box2~><p><label id=~lbl" + i + "~>" + Email.ToString() + "</label><label class=~SentInvitationLbl~ id=~lblSentInvitation" + i + "~>" + SentInvitation + "</label></p></div><div class=~friend_list_box3~></div><div class=~clear~></div></div>";
else
HTML += "<div class=~other_wish_row3~><div class=~friend_list_box1~><input type=~checkbox~ class=~chkEmail~ id=~chkId^" + i + "~/></div><div class=~friend_list_box2~><p><label id=~lbl" + i + "~>" + Email.ToString() + "</label><label class=~SentInvitationLbl~ id=~lblSentInvitation" + i + "~>" + SentInvitation + "</label></p></div><div class=~friend_list_box3~></div><div class=~clear~></div></div>";
i = i + 1;
}
ScriptManager.RegisterStartupScript((Page)(HttpContext.Current.Handler), typeof(Page), "hdrEmpty1", "Test('" + HTML + "');", true); return;
}
else
{
}
}
Jquery Code is:
function Test(data) {
alert('hi');
}
function Binddata(SocialSite) {
$.ajax({
type: "POST",
url: "InviteFriends.aspx/BindData",
data: "{SocialSite:'" + SocialSite + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
}
});
}
I am not able to fire Test(), please help to resolve this.
You can't do this from a web service (either an .asmx file or a WebMethod) as it does not run in the context of a normal page. I see you're using AJAX, you'll have to do the handling in the success callback method of your jQuery.ajax() call, like so:
function Test(data) {
alert('hi');
}
function Binddata(SocialSite) {
$.ajax({
type: "POST",
url: "InviteFriends.aspx/BindData",
data: "{SocialSite:'" + SocialSite + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
Test(data);
}
});
}

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

how to fetch return values between jquery functions and post ajax jquery request to webservice

I have the following code where the function codeaddress geocodes the text feild value and returns geocoded value , geocoded value is stored in variable example ,how will i return the variable v2 to the function call and post to asmx webservice.
<script type="text/javascript">
$(document).ready(function() {
$('#SubmitForm').submit(function() {
var geocoder;
var map;
function codeAddress(state) {
var address = document.getElementById("state").value;
geocoder.geocode( { 'address': state}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var v2=results[0].geometry.location;
alert(example);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
return v2;
});
var businessname = ($("#businessname").val());
var keyword = ($("#keyword").val());
var description = ($("#textarea").val());
var zipcode = ($("#zipcode").val());
var streetno = ($("#streetno").val());
var streetname = ($("#streetname").val());
var state = $('#state :selected').text();
var telephone = ($("#telephone").val());
var email = ($("#email").val());
var username = ($("#username").val());
var password = ($("#pass").val());
var repassword = ($("#pass1").val());
//data: "{'businessname':" + businessname + "'keyword':" + keyword + "}",
alert(state);
var v2=codeAddress(state);
alert(example);
var jsonobject = "{\"businessname\":\"" + businessname + "\",\"keyword\":\"" + keyword + "\",\"description\":\"" + description + "\",\"zipcode\":\"" + zipcode + "\",\"streetno\":\"" + streetno + "\",\"streetname\":\"" + streetname + "\",\"state\":\"" + state + "\",\"telephone\":\"" + telephone + "\",\"email\":\"" + email + "\",\"username\":\"" + username + "\",\"password\":\"" + password + "\",\"repassword\":\"" + repassword + "\"}";
$.ajax({
type: "POST",
url: "/BlockSeek/jsonwebservice.asmx/SubmitList",
data: jsonobject,
contentType: "application/json; charset=utf-8",
success: ajaxCallSucceed,
dataType: "json",
failure: ajaxCallFailed
});
});
function ajaxCallFailed(error) {
alert("error");
}
function ajaxCallSucceed(response) {
if (response.d == true) {
alert(" sucessfully saved to database");
}
else {
alert("not saved to database");
}
}
});
</script>
You call the codeAddress method with a callback. Inside codeAddress when you get value of v2, call the callback function passing it v2.
codeAddress(state,
function(v2) {
var jsonobject = "{\"businessname\":\"" + businessname/*.. use v2 in buiding jsonobject..*/;
$.ajax({
type: "POST",
url: "/BlockSeek/jsonwebservice.asmx/SubmitList",
data: jsonobject,
contentType: "application/json; charset=utf-8",
success: ajaxCallSucceed,
dataType: "json",
failure: ajaxCallFailed
});
}
);
function codeAddress(state, callback) {
var address = document.getElementById("state").value;
geocoder.geocode(...);
// ...
var v2=results[0].geometry.location;
callback(v2);
}

Categories

Resources