Json result Not Binding to aspx? - c#

I have a service and it is returning json in the following format
Data {
"TerminalID": 21,
"TerminalName": "NewTested",
"PortID": 27,
"PortName": "Badu Island",
"EffectiveStart": "2013-03-20T00:00:00",
"EffectiveEnd": "2013-03-23T00:00:00",
"ServiceID": 2
}
and in my aspx page my code is:
<script type="text/javascript">
$(document).ready(function () {
$("#divImageGo").click(function () {
var valId = 2;
$.ajax({
type: "GET",
url: "VoyageOneService.svc/BindVoyageDetails" + valId,
//data: '{"ServiceID":"2"}',
processData: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
ServiceSucceeded(result);
},
error: function (msg) {
$("#errorDiv").text(msg);
}
});
});
});
And success does the following:
function ServiceSucceeded(data) {
alert("Success");
for (var i = 0; i < data.d.length; i++) {
$("#dlistVoyageDetails").append("<tr><td>" + data.d[i].TerminalName + "</td><td>" + data.d[i].PortName + "</td><td>" + data.d[i].EffectiveStart + "</td></tr>" + data.d[i].EffectiveEnd + "</td></tr>");
}
}
function ServiceFailed(xhr) {
if (xhr.responseText) {
var err = xhr.responseText;
if (err)
error(err);
else
error({ Message: "Unknown server error." })
}
return;
}
In this ..,
Iam getting My service called
Iam getting my Return value of json
Iam getting the Success fired with its alert msg
But I am unable to get the result. When I checked my alert with the result I am getting NULL

Remove the if condition and it will work.
As data.length is null hence you condition is not satisfied.
function ServiceSucceeded(data) {
alert("Success");
$("#dlistVoyageDetails").append("<tr><td>" + data.d[i].TerminalName + "</td><td>" + data.d[i].PortName + "</td><td>" + data.d[i].EffectiveStart + "</td></tr>" + data.d[i].EffectiveEnd + "</td></tr>");
}

Related

Get next 8 rows from database on button click using linq to sql and web method

I am creating a webpage in which I fetch top 8 rows from database on page load. I put load more button on my bottom of my web page. What I want is when I click on load more button it shows me next new 8 rows and skip previous records and if there is no new record found then show me nothing.
Below is my code which I was trying but it was repeating same duplicate records.
//Below event is fetching top 8 rows on page load
function viewAllEvents() {
$.ajax({
url: "Event.aspx/viewEvents",
data: null,
contentType: "Application/json; charset=utf-8",
responseType: "json",
method: "POST",
success: function (response) {
var x = response.d;
for (var i = 0; i < x.length; i++) {
$("#tabss > .event-container > .row").append(
"<div class='col-md-3'><div class='event'><div class='eventsimg'><img src= " + '../MediaUploader/' + x[i].EVE_IMG_URL + " alt=''></div><div class='event-content'><h3 class='title'>" + x[i].EVE_NAME + "</h3><p>" + x[i].EVE_DESCRIPTION + "</p><input type='button' id=" + i + " class='btn btn-pri' style='padding: 9px 9px;font-size: 12px;' onClick='eveReq(" + i + ", " + x[i].ID + ", " + x[i].EVE_CAT_ID + ");' value='Send Request' /><input type='button' class='btn btn-pri' style='padding: 9px 9px;font-size: 12px;margin-left: 2px;' value='Read More' /></div><div class='links clearfix'></div></div></div>"
);
}
},
error: function (xhr) {
alert(xhr.status);
},
Failure: function (response) {
alert(response);
}
});
}
//Below event is for when load more button is clicked
function addTabs() {
$.ajax({
url: "Event.aspx/addTab",
data: null,
contentType: "Application/json; charset=utf-8",
responseType: "json",
method: "POST",
success: function (response) {
var x = response.d;
for (var i = 0; i < x.length; i++) {
$("#tabss > .event-container > .row").append(
"<div class='col-md-3'><div class='event'><div class='eventsimg'><img src= " + '../MediaUploader/' + x[i].EVE_IMG_URL + " alt=''></div><div class='event-content'><h3 class='title'>" + x[i].EVE_NAME + "</h3><p>" + x[i].EVE_DESCRIPTION + "</p><input type='button' id=" + i + " class='btn btn-pri' style='padding: 9px 9px;font-size: 12px;' onClick='eveReq(" + i + ", " + x[i].ID + ", " + x[i].EVE_CAT_ID + ");' value='Send Request' /><input type='button' class='btn btn-pri' style='padding: 9px 9px;font-size: 12px;margin-left: 2px;' value='Read More' /></div><div class='links clearfix'></div></div></div>"
);
}
},
error: function (xhr) {
alert(xhr.status);
},
Failure: function (response) {
alert(response);
}
});
}
Below is my web methods:
[WebMethod]
public static List<EVENT> viewEvents()
{
var slist = new List<EVENT>();
var db = new BLUEPUMPKINEntities();
db.Configuration.LazyLoadingEnabled = false;
slist = db.EVENTS.OrderByDescending(eve => eve.ID).Take(8).ToList();
return slist;
}
[WebMethod]
public static List<EVENT> addTab()
{
var slist = new List<EVENT>();
var db = new BLUEPUMPKINEntities();
db.Configuration.LazyLoadingEnabled = false;
slist = db.EVENTS.OrderByDescending(eve => eve.ID).Skip(8).Distinct().ToList();
return slist;
}
Though I didn't use your code but I believe if you can go through this example below then you'll know what to do:
First declare a global variable which will count the record returned so far:
private int recordCount = 0;
Then in the click event do the following:
//My sample data
int[] data = { 1, 2, 3, 4, 5, 6, 7, 8 };
var results = data.Skip(recordCount).Take(2);
//Increment recordCount by the count of the results return above
recordCount+= results.Count();
if (results.Count() > 0)
{
//return results
}

How to get autocomplete data correctly formatted

Using .NET here's what I've got.. The right results are returned, but they're all combined together into one long string. How can I make it so I can select one item at a time from the results returned? I know my source in the javascript is configured incorrectly. Any help would be appreciated. Thanks
Code behind:
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public static string[] GetEmails(string emailContains)
{
LoginSet logins = staticLogic.searchLogins(staticClient, new SearchCriteriaSet());
List<BaseEntry> loginList = logins.Where(x => ((LoginEntry)x).LoginEMail.Contains(emailContains)).ToList();
List<string> emails = new List<string>();
for (int i = 0; i < loginList.Count(); ++i)
{
string email = ((LoginEntry)loginList.ElementAt(i)).LoginEMail;
emails.Add(email);
}
//JavaScriptSerializer serializer = new JavaScriptSerializer();
//string json = serializer.Serialize(emails.ToArray());
return emails.ToArray();
}
UI:
<tr><td>Destination:</td>
<td>
<div class="ui-widget">
<input type="text" name="EMailReportDestination" id="EMailReportDestination" size="60" runat="server" />
</div>
</td>
</tr>
JQuery:
$('#EMailReportDestination').autocomplete({
source: function (request, response) {
$.ajax({
url: '/reports/editemailreport.aspx/GetEmails',
type: 'POST',
dataType: 'json',
data: "{'emailContains':'" + request.term + "'}",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
//console.log('autocomplete success: ' + data);
response($.map(data, function (item) {
return {
label: item,
value: item
}
}));
},
error: function (xhr, ajaxOptions, thrownError) {
console.log("autocomplete error: " + xhr.status + ", " + thrownError);
}
});
},
minLength: 2,
select: function (event, ui) {
console.log(ui.item ? "selected: " + ui.item.label : "nothing selected, input was " + this.value);
},
open: function () {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function () {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
I tried and I don't know array returned in data.d. try to change
response($.map(data, function (item)
to
response($.map(data.d, function (item)

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

jquery post going in loop

I've this code which I'm using to post a message on 'Enter' key press, but it's going on loop and instead of posting one message it's posting it multiple times randomly.
This is the function I'm calling in on <input id='txtsendmsg" + i + "' placeholder=\"Write a comment...\" onkeypress='PostMessage(event,"+i+");' class='msgtxt'></input> any help would be appreciated.
function PostMessage(event,key) {
$('#txtsendmsg'+key).on("keypress", function (e) {
if (e.which == 13) {
var msgid = $(this).siblings('.msgid').val();
var msgtxt = $(this).val();
$.ajax({
url: "student_post_login.aspx/funPostMessage",
data: 'postd=' + "Y" + '&msgid=' + msgid + '&msgtxt=' + msgtxt,
success: function (data) {
if (data) {
displayData();
}
},
failure: function (response) {
alert("Faliure:");
},
error: function (response) {
alert(response);
}
});
e.preventDefault();
}
});
}
The problem is because you are attaching an event handler every time you hit the a key in the input field. Press a key twice and you get two requests sent, three times; three and so on.
Try assigning the handler using jQuery only instead of the onclick attribute:
<input id='txtsendmsg" + i + "' placeholder=\"Write a comment...\" class='msgtxt' />
$('.msgtxt').on('keypress', function (e) {
var $el = $(this);
if (e.which == 13) {
var msgid = $el.siblings('.msgid').val();
var msgtxt = $el.val();
$.ajax({
url: "student_post_login.aspx/funPostMessage",
data: 'postd=' + "Y" + '&msgid=' + msgid + '&msgtxt=' + msgtxt,
success: function (data) {
if (data) {
displayData();
}
},
failure: function (response) {
alert("Faliure:");
},
error: function (response) {
alert(response);
}
});
e.preventDefault();
}
});

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