Jquery webservice foreach loop - c#

I'm trying to jquery dropdownlist with this result set of webservice, the getYears function is returning list of years 2013,2012,2011.... in List<string> for but when I bind it with ddlyears the values coming up as 1,2,3,4,5,6
$.ajax({
type: "POST",
url: "../WebService.asmx/getYears",
data:"{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (msg) {
for (var myVar in msg.d) {
$('#ddlyears').append("<option value='" + myVar.toString() + "'>" + myVar.toString() + "</option>");
}
},
error: function (jqerr) {
errorCaller(jqerr);
}
});

Try this:
success: function (msg) {
$.each(msg.d, function (k, value) {
$('#ddlyears').append("<option value='" + value + "'>" + value + "</option>");
});
}

Related

can't redirect method from ajax method to aspx.cs page

I have following code in my CenterDetail.aspx page
function myFunction(id) {
console.log(2);
var myindex = window.ContentPlaceHolder1_ddCountryId.selectedIndex;
console.log(myindex);
var selectedName = window.ContentPlaceHolder1_ddCountryId.options[myindex].text;
console.log(selectedName);
var loc = window.location.href;
console.log(loc);
$.ajax({
type: "POST",
url: loc + "/BindState",
data: { id : id },
async: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
console.log(data);
}
});
}
and following method is in my code behind file.
[WebMethod]
public static string BindState(int id)
{
var states = new StateProvinceCollection().Where(StateProvince.Columns.CountryId = Convert.ToString(id), true).ToList();
string tag = "<select id='StateProvinceId' name='StateProvinceName'>";
tag += "<option value=''>select</option>";
foreach (var item in states)
{
tag += "<option value='" + item.StateProvinceId + "'>" + item.StateProvinceName + "</option>";
}
tag += "</select>";
return tag;
}
everything is still it show http://musicclass/Account/Management/Center/CenterDetail.aspx/BindState 404 not found error.

How to call Web Method using Jquery Ajax

I am using ajax to call a [WebMethod].But it doesn't Works.Code i used is
ASPX page
$.ajax({
type: "POST",
url: '<%= ResolveUrl("~/CandidateManagement.aspx/GetCurrentDateTime") %>',
data: '{name: "' + document.getElementById("lbcb5").innerHTML + '" }', Value
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
Aspx.cs page
[WebMethod]
public static string GetCurrentDateTime(string name)
{
return "Hey! " + name + Environment.NewLine + "The Current Date & Time is: "
+ DateTime.Now.ToString();
}
Thanks in advance
you don't need quotes on data, do like this:
$.ajax({
type: "POST",
url: '<%= ResolveUrl("~/CandidateManagement.aspx/GetCurrentDateTime") %>',
data: {name: document.getElementById("lbcb5").innerHTML},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response)
{
alert(response)
},
failure: function (response) {
alert(response.d);
}
});
Did you add a ScriptManager in you aspx page?
I think you should try to add it with the attribute EnablePageMethods="true"
try this:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />
"When i use ScriptManager shows an error Only one instance of a ScriptManager can be added to the page."
when this type of error is thrown, then use scriptmanager proxy
<ajax:ScriptManagerProxy ID="ScriptManagerProxy1" runat="server">
</ajax:ScriptManagerProxy>
--------------************DEFAULT.ASPX************--------------
<script type="text/javascript">
function YolAl(yol) {
deger='<%=ResolveUrl("~/'+ yol +'") %>'
return deger;
}
</script>
*******************------USERCONTROL CALL JS-------************************
$(window).scroll(function () {
if ($(window).scrollTop() == $(document).height() - $(window).height()) {
deger += 1;
RepeaterFnc("BaglantiItem.ascx", deger, "BagListDiv", YolAl('Default.aspx/AddGadGets'));
}
});
$(document).ready(function () {
deger += 1;
RepeaterFnc("DurumGuncelle.ascx", deger, "BagListDiv", YolAl('Default.aspx/AddGadGets'));
RepeaterFnc("IlanlarTab.ascx", deger, "SolDivAlanId", YolAl('Default.aspx/AddGadGets'));
RepeaterFnc("BaglantiItem.ascx", deger, "BagListDiv", YolAl('Default.aspx/AddGadGets'));
RepeaterFnc("Top10TakipEt.ascx", deger, "SagDivFavoriId", YolAl('Default.aspx/AddGadGets'));
RepeaterFnc("Top10Ilanlar.ascx", deger, "SolDivAlanId", YolAl('Default.aspx/AddGadGets'));
});
function TakipEtYenileFnc() {
$('#SagDivFavoriId').html('');
RepeaterFnc("Top10TakipEt.ascx", deger, "SagDivFavoriId", YolAl('Default.aspx/AddGadGets'));
}
function RepeaterFnc(usercontrol, deger, DivName,FuncName) {
$('#ajaxloading').show();
var NextId = deger;
$.ajax({
url: FuncName,
type: "POST",
data: "{usercontrol:'" + usercontrol + "', NextId:'" + NextId + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
OnSuccess1(msg, DivName);
},
error: function (msg) { OnError1(DivName); }
});
deger = parseInt(deger + 1);
}
function OnSuccess1(data, DivName) {
$("#" + DivName).html($("#" + DivName).html() + data.d);
$('#ajaxloading').hide();
}
function OnError1(divname) {
return false;
$("#" + divname).html("Error!");
}

Ajax complete function issue

I'm working on my collage project (Web app written in C#) and I'm using javascript
to dynamically add hotels with details and image using following code:
$.ajax({
type: 'POST',
url: 'WebServiceBooking.asmx/Hotels',
data: "{'stars':'" + stars + "','countryid':'" + country + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$('.hotels').empty();
var hotels = data.d; //getting List<Hotel> from [WebMethod](works)
window.t = "";
window.ImageID = "";
$.each(hotels, function (index, hotel) {
$.ajax({ //this ajax is getting Image for specified hotel.HotelID
type: 'POST',
url: 'WebServiceBooking.asmx/HotelImage',
data: "{'hotelid':'" + hotel.HotelID + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
window.ImageID = data.d;
//$('.hotels-image').attr('src', 'ImageHandlerFromID.ashx?ImageID=' + data.d);
},
complete: function (xhr, status) {
window.t += "<div class='hotel clearfix'><h3><a href='hotel.aspx?HotelID=" + hotel.HotelID + "'>" + hotel.HotelName + "</a></h3><p class='hotelAddress'>" + hotel.HotelAddress + "</p><p class='hotelPhone'>" + hotel.HotelPhone + "</p>";
window.t += "<img class='hotels-image' src='ImageHandlerFromID.ashx?ImageID=" + window.ImageID + "'/>";
window.t += "</div>";
console.log(window.ImageID);
}
});
console.log(ImageID);
});
console.log(window.t);
},
complete: function (xhr, status) {
$('.hotels').append(window.t);
}
});
After several attempts, neither complete function works.
The complete call will only complete the first ajax call. Not the one's in the for loop. If you want to check if all requests are done use $.when.
var requests = [];
var overall_data = {"hotels" = [], "hotel_images" = []}
var main_request = $.ajax({
type: 'POST',
url: 'WebServiceBooking.asmx/Hotels',
data: "{'stars':'" + stars + "','countryid':'" + country + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$('.hotels').empty();
var hotels = data.d; //getting List<Hotel> from [WebMethod](works)
overall_data["hotels"] = hotels
window.t = "";
window.ImageID = "";
$.each(hotels, function (index, hotel) {
var hotel_request = $.ajax({ //this ajax is getting Image for specified hotel.HotelID
type: 'POST',
url: 'WebServiceBooking.asmx/HotelImage',
data: "{'hotelid':'" + hotel.HotelID + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
window.ImageID = data.d;
overall_data["hotel_images"].push(data)
//$('.hotels-image').attr('src', 'ImageHandlerFromID.ashx?ImageID=' + data.d);
}
});
requests.push(hotel_request)
console.log(ImageID);
});
console.log(window.t);
}
});
requests.push(main_request);
$.when.apply(null, requests).done(function(){
// Do your stuff with overall_data
})

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

call method in code behind from JQuery

I am trying to execute a method in ASP.NET from Jquery
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "MyMessages.aspx?id=66&epslanguage=sv/test",
data: "{}",
dataType: "json",
error: function(xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
},
success: function() {
alert("it works" );
}
})
code behind:
[WebMethod]
protected void test()
{
test.Text = "works";
}
I get errormessage redayState: 4 and status 200 when I do this. I don't understand the problem. I am vey new at this. :)
data: "{}", should be just data: {}, or just remove it if not in use,,..
as a first your method should be static and public
so instead of this
[WebMethod]
protected void test()
{
test.Text = "works";
}
it should be
[WebMethod]
public static void test()
{
test.Text = "works";
}
this is the first fix
the second you can't access the test.text
so if u wanna make sure it works you can
write it in this way
$.ajax({
type: "POST",
contentType: "application/json",
url: "MyMessages.aspx/test",
data: "{}",
dataType: "json",
error: function(xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
},
success: function() {
alert("it works" );
// and here use jQuery to set the control test
$("#<%=test.ClientID%>".text("Works");
}
})
so your final code should be like this
[WebMethod]
public static void test()
{
//test.Text = "works";
}
and Ajax method
$.ajax({
type: "POST",
contentType: "application/json",
url: "MyMessages.aspx/test",
data: "{}",
dataType: "json",
error: function(xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
},
success: function() {
alert("it works" );
// and here use jQuery to set the control test
$("#<%=test.ClientID%>".text("Works");
}
})
I did change the URL for u
and if you wanna pass parameters you pass them on Data Section of Ajax method
some thing like this
'{"fname":"' + fname + '","lname":"' + lname + '","email":"' + email + '","address":"' +
I wish it helps you
address + '"}'

Categories

Resources