Infinite scroll with ASP.NET Web Forms using PageMethods - c#

I've been trying to make something like an infinite scroll work but with no success. And after searching a lot around the web i'm asking the question myself.
About the code,
In the masterPage.Master i've put:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
On another page in the code behind i have a method like this that is going to be called by the script:
[System.Web.Services.WebMethod()]
[System.Web.Script.Services.ScriptMethod()]
public static List<agendaList> GetEvents(int startAt, int howMany)
{
...
return eventsListNew.OrderByDescending(p => p.data).Skip(startAt).Take(howMany).ToList<agendaList>();
}
In the page i added the script:
<script type="text/javascript">
$(document).ready(function () {
$(window).scroll(function () {
if ($(window).scrollTop() == $(document).height()-$(window).height()) {
GetEvents();
}
});
});
function GetEvents() {
var howMany = 10;
var startAt = $(".mason_script").size();
console.log(startAt);
PageMethods.GetEvents(startAt, howMany);
}
function OnGetPostsComplete(Events) {
for (var i = 0; i < Events.length; i++) {
$("#list_eventos_content").last().append("<ul>"+
Events[i].title + "</h2><p>" +
Events[i].data + "</p></div>" + "</ul>");
}
}
</script>
It says PageMethods is not defined!
Specifically in the console i get:
Uncaught ReferenceError: PageMethods is not defined
I tryed using the ajax method but with no success either:
<script type="text/javascript">
$(document).ready(function () {
$(window).scroll(function () {
var howMany = 10;
var startAt = $(".mason_script").size();
if ($(window).scrollTop() == $(document).height() - $(window).height()) {
//GetEvents();
console.log(startAt);
$.ajax({
type: "POST",
//async: true,
url: "default.aspx/GetEvents",
//url: '<%= ResolveUrl("ConsultaPedidos.aspx/GetClients") %>',
//data: {startAt:startAt,howMany:howMany},
data: JSON.stringify({ startAt: startAt, howMany: howMany }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () { alert("success"); },
error: function () {alert("it was not a success");}
});
}
});
});
</script>
I think the website is already ajax enabled because it's done with visual studio 2010 and i think i have all the necessary bins (i even added System.Web.Extensions.dll to project)
I don't know if this helps to find the problem, but inside the source code after the body element i have the following:
<body id="body" class="home">
<div>
<form method="post" action="./Default.aspx" id="form1">
<div class="aspNetHidden">
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMTY1NDU2MTA1Mg9kFgJmD2QWAgIDDxYCHgVjbGFzcwUEaG9tZRYCAgEPZBYIAgQPFgIeB1Zpc2libGVoZAIFD2QWBAIDDxYCHwFoZAIFDxYCHwFoZAIIDxYCHwFoZAIJD2QWAmYPFgIfAWhkZHECEx2bRG9W3HRdtf7e7U4T5JxcYTUIOFqhiAfLIgzr" />
</div>
<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['form1'];
if (!theForm) {
theForm = document.form1;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
//]]>
</script>
<script src="/WebResource.axd?d=eTLIdTUaKcPvbbHq3uBMJMuE5EuUKGo_QXsf5WdWsog2Gpmfy9qkIK_-y74XUCFlxJFADxQgAgshTA379vvKJGJvi4Ikqiv1yEvS7hpyqVc1&t=635918767619348548" type="text/javascript"></script>
<script src="/ScriptResource.axd?d=qkRHwPohnv0qxNzn-8f9Xk8Z0dBG23n8MDuOOCYf4anPCmyRNRWeCNNgCauDnRlVqW5NKLUOVIfNjW56x6pHNSKmtX7CBH7SpCqDvmzy-NHrCoITbgWSVLGcKILzzGQ1Qlpwpc9IIxnLVQ51v9Kz9DCgKlPHgukhQEeDMmKkQtiLHT1xZPJVocodYa8aG11L0&t=40eb3b32" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
if (typeof(Sys) === 'undefined') throw new Error('Falha ao carregar estrutura ASP.NET Ajax do lado do cliente.');
//]]>
</script>
<script src="/ScriptResource.axd?d=gU20UmsqL_uPpdXkHzmyFnlCqFiRG-TM2_Qv0ZALZUtlYUJwYdUdoCXOyXFrEkZWVT92wbL9D1m0HngfHHZW6U8GVV-j6jTKDIjQ4UrIHIXmsJyijp8fEm7m7Qeq-8buVg1yHzCv2Zqt_ktAHum363tvYlDt3B2fmD8Q3YF2jvkK8HbizNFHmiEcaIil3BlR0&t=40eb3b32" type="text/javascript"></script>
<div class="aspNetHidden">
<input type="hidden" name="__VIEWSTATEGENERATOR" id="__VIEWSTATEGENERATOR" value="CA0B0334" />
<input type="hidden" name="__SCROLLPOSITIONX" id="__SCROLLPOSITIONX" value="0" />
<input type="hidden" name="__SCROLLPOSITIONY" id="__SCROLLPOSITIONY" value="0" />
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEdAALKL6JprTutrB5uCf6KA5FA2RsWv7CsEAlbyK1tt2kzFFESTmnJ8bzYWS2HmzbItmQmobFjEmOUyk9VeVTmAEW9" />
</div>
<input type="hidden" name="ctl00$hidMenu" id="hidMenu" value="menu_home" />
<script type="text/javascript">
//<![CDATA[
Sys.WebForms.PageRequestManager._initialize('ctl00$ScriptManager1', 'form1', [], [], [], 90, 'ctl00');
//]]>
</script>
Only then comes the rest of the page and the script that calls the PageMethod.
Thanks

Related

Cannot see from code behind the values of Dynamically created textboxes using AngularJS

I am new to AngularJS programming. Any help would be highly appreciated.
A HTML text box will be created each time a HTML button is clicked.
In webform1.aspx submit button click even cannot capture the values entered in those text boxes.
I used request.form, loop through controls in the form1 but cannot find dynamically created controls.
How to post and see the data entered in those textboxes from code behind?
Please find the code below:
webform1.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://raw.githubusercontent.com/eligrey/FileSaver.js/master/FileSaver.js"></script>
</head>
<body>
<form id="form1" runat="`server">
<div>
<div ng-app="myApp" ng-controller="myCtrl">
<li ng-repeat="element in elements ">
<input type="text" ng-model="element.id" runat=server/>
</li>
<input type="button" value="+" ng-click="newItem()" />
</div>
</form>
</body>
<script language="JavaScript">
var app = angular. Module('myApp', []);
app.controller('myCtrl', function ($scope) {
var counter = 0;
$scope.elements = [{ id: counter, value: ''}];
$scope.newItem = function () {
if ($scope.elements[counter].value != '') {
counter++;
var str1 = 'txtdynamic';
str1 += counter;
$scope.elements.push({ id: str1, value: '' });
}
}
});
</script>
</html>
webform1.aspx.cs
protected void Button2_Click(object sender, EventArgs e)
{
//get the html ng repeat textbox control values
}
Try it the right way my friend. Compare the following codes with your approach.
> demo fiddle.
View
<div ng-controller="myCtrl">
<form id="form1" runat="`server">
<div>
<div ng-app="myApp" ng-controller="myCtrl">
<li ng-repeat="element in elements">
<input type="text" ng-model="elements[element.id].value" runat=server/>
</li>
<input type="button" value="+" ng-click="newItem()" />
<input type="button" value="send" ng-click="ButtonClick()" />
</div>
</div>
</form>
</div>
AngularJS application
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
var counter = 0;
$scope.elements = [{
id: counter,
value: ''
}];
$scope.newItem = function() {
if ($scope.elements[counter].value != '') {
counter++;
var str1 = 'txtdynamic';
str1 += counter;
$scope.elements.push({
id: str1,
value: ''
});
}
}
$scope.ButtonClick = function() {
var post = $http({
method: "POST",
url: "/Home/AjaxMethod",
dataType: 'json',
data: {
id: angular.isDefined($scope.elements[0]) ? $scope.elements[0].value : null
},
headers: {
"Content-Type": "application/json"
}
});
}
});

SheepIt: find id of each control and bind dropdownlist with database using asp.net

I am working on an asp.net application where i am using SheepIt plugin to dynamically generate controls like textboxes and dropdownlist.I want to bind textboxes with jquery-ui-calender and I want to bind dropdownlist with the database items. My code is:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script type="text/javascript" src="jquery-1.4.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css" />
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<!--<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>-->
<script type="text/javascript" src="jquery.sheepItPlugin.js"></script>
<script type="text/javascript">
var sheepItForm = {};
$(document).ready(function () {
sheepItForm = $('#sheepItForm').sheepIt({
separator: '',
allowRemoveLast: true,
allowRemoveCurrent: true,
allowRemoveAll: true,
allowAdd: true,
allowAddN: true,
maxFormsCount: 10,
minFormsCount: 0,
iniFormsCount: 0,
afterAdd: function (source, newForm) {
$(".from").datepicker({
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 1,
onClose: function (selectedDate) {
$(".to").datepicker("option", "minDate", selectedDate);
}
});
$(".to").datepicker({
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 1,
onClose: function (selectedDate) {
$(".from").datepicker("option", "maxDate", selectedDate);
}
});
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "SheepingExample.aspx/BindDatatoDropdown",
data: "{}",
dataType: "json",
success: function (data) {
$.each(data.d, function (key, value) {
$("#sheepItForm_#index#_ddlRoom").append($("<option></option>").val(value.ID).html(value.Name));
});
}
});
}
});
});
</script>
<style>
a {
text-decoration: underline;
color: #00F;
cursor: pointer;
}
#sheepItForm_controls div, #sheepItForm_controls div input {
float: left;
margin-right: 10px;
}
#executeLink {
clear: both;
margin-top: 20px;
}
</style>
</head>
<body>
<!-- sheepIt Form -->
<div id="sheepItForm">
<!-- Form template-->
<div id="sheepItForm_template">
<label for="sheepItForm_#index#_phone">Booking Details <span id="sheepItForm_label"></span></label>
<input id="sheepItForm_#index#_phone" name="person[phones][#index#][phone]" type="text" size="15" maxlength="10" style="display: none;" />
<select id="sheepItForm_#index#_ddlRoom" name="person[phones][#index#][ddlRoom]" class="sel"></select>
<input id="sheepItForm_#index#_from" class="from" placeholder="Enter From Date" name="person[phones][#index#][from]" type="text" size="15" maxlength="10" />
<input id="sheepItForm_#index#_to" class="to" placeholder="Enter to Date" name="person[phones][#index#][to]" type="text" size="15" maxlength="10" />
<a id="sheepItForm_remove_current">
<img class="delete" src="images/cross.png" width="16" height="16" border="0">
</a>
</div>
<!-- /Form template-->
<!-- No forms template -->
<div id="sheepItForm_noforms_template">No phones</div>
<!-- /No forms template-->
<!-- Controls -->
<div id="sheepItForm_controls">
<div id="sheepItForm_add"><a><span>Add phone</span></a></div>
<div id="sheepItForm_remove_last"><a><span>Remove</span></a></div>
<div id="sheepItForm_remove_all"><a><span>Remove all</span></a></div>
<div id="sheepItForm_add_n">
<input id="sheepItForm_add_n_input" type="text" size="4" />
<div id="sheepItForm_add_n_button"><a><span>Add</span></a></div>
</div>
</div>
<!-- /Controls -->
</div>
<!-- /sheepIt Form -->
</body>
</html>
and My webservice to bind dropdownlist database-items is:
[WebMethod]
public static RoomType[] BindDatatoDropdown()
{
DataTable dt = new DataTable();
List<RoomType> details = new List<RoomType>();
using (SqlConnection con = new SqlConnection(#"Data Source=.\sqlexpress;Initial Catalog=Raju;Integrated Security=true"))
{
using (SqlCommand cmd = new SqlCommand("SELECT ID,Name FROM RoomType_Master", con))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
RoomType room = new RoomType();
room.ID = 0;
room.Name = "select";
details.Add(room);
foreach (DataRow dtrow in dt.Rows)
{
RoomType country = new RoomType();
country.ID = Convert.ToInt32(dtrow["ID"].ToString());
country.Name = dtrow["Name"].ToString();
details.Add(country);
}
}
}
return details.ToArray();
}
but when i try to bind dropdownlist with its id then is not getting bind. Also it not giving any error. please help me someone.
In jQuery, the $(document).ready() function expects all the elements to be loaded in the DOM. Any dynamically loaded elements will be ignored and that's why it won't bind; it can't find the element on the page. There are alternate methods in jQuery (see docs) or you can re-register the scripts.
If using MVC razor:
#if(Request.IsAjaxRequest()){
<script>...</script>
}
If using WebForms, use ClientScriptManager.RegisterClientScriptBlock.
In jQuery, you can use event delegation like so:
$('<selector>').on('click', '#target', function(){…});

Javascript function is not working on asp:button Click event, where a test alert function works.!

I am trying to create an alert as described in this site http://needim.github.com/noty/
and here is the code
<head runat="server">
<title>Test</title>
<script src="jquery-1.7.2.min.js" type="text/javascript"></script>
<script type="text/javascript" src="js/noty/jquery.noty.js"></script>
<script type="text/javascript" src="js/noty/layouts/top.js"></script>
<link rel="stylesheet" type="text/css" href="buttons.css" />
<script type="text/javascript" src="js/noty/themes/default.js"></script>
</head>
<body>
<div class="container">
<div id="customContainer">
</div>
</div>
<script type="text/javascript">
function generate(type, layout) {
var n = noty({
theme: 'defaultTheme',
text: 'Do you want to continue?',
buttons: [
{
addClass: 'btn btn-primary',
text: 'Ok',
onClick: function ($noty) {
// this = button element
// $noty = $noty element
$noty.close();
noty(
{
text: 'Record deleted !',
type: 'success',
callback:
{
onShow: function () { },
afterShow: function () { TakeValue(true); },
onClose: function () { },
afterClose: function () { }
}
});
}
},
{
addClass: 'btn btn-danger',
text: 'Cancel',
onClick: function ($noty) {
$noty.close();
noty(
{
text: 'Record not deleted !',
type: 'warning',
callback:
{
onShow: function () { },
afterShow: function () { TakeValue(false); },
onClose: function () { },
afterClose: function () { }
}
});
}
}
]
});
}
function TakeValue(result) {
if (result == true) {
document.getElementById("Hidden1").value = "true";
alert(document.getElementById("Hidden1").value);
} else {
document.getElementById("Hidden1").value = "false";
alert(document.getElementById("Hidden1").value);
}
}
function generateAll() {
generate('information', 'top');
}
</script>
<form id="form" runat="server">
<input id="Hidden1" type="hidden" value="false"/>
<asp:Button ID="Button2" runat="server" Text="Press" OnClientClick="return generateAll();" />
<input id="Button1" type="button" value="button" onclick="return generateAll();" />
</form>
</body>
I have placed two buttons ,one is HTML button while the other is of asp:Button,
The whole scenario just works fine when I use the HTML button ,but the page is not displaying the similar behavior in case of asp:Button click, I have placed a test function in JavaScript to test the OnClientClick event of the asp:Button and that worked fine,but I don't know why this alert is not getting called, I think there is some problem with the Noty JS.
Kindly give feed back
thanks.
As jbabey said in the comments:
an asp:button will cause a postback when clicked by default. you need to return false from the onclientclick, right now you are returning undefined since generateAll has no return.
Since you're using jQuery, I'd go one step further and not directly set the click attribute. Instead, set it using jQuery:
<script>
$(document).ready(function() {
$('#Button1').click(generateAll);
});
...
function generateAll(e) {
generate('information', 'top');
// This will prevent the default action of submitting the form.
e.preventDefault();
}
</script>
Could you please add UseSubmitBehavior="false" attribute to the asp:button.
<asp:Button ID="Button2" runat="server" Text="Press" UseSubmitBehavior="false" OnClientClick="return generateAll();" />
I hope this will resolve your issue. Please let me know whether it helped you or not.

Dialog Box appears and then disappears

When I click on the button Dialog Box it appears and disappears, I tired using different plugins and hundreds of tutorial but dunno why things not working properly maybe because, I am using ASP.Net page and its inheriting from a masterpage
here's the code,
<asp:Content ID="Content4" ContentPlaceHolderID="cphSubmit" runat="server">
<div id="question" style="display:none; cursor: default">
<h1>Would you like to contine?.</h1>
<input type="button" id="yes" value="Yes" />
<input type="button" id="no" value="No" />
</div>
<input id="test" type="submit" value="Show Dialog" />
<script type="text/javascript" src="/_layouts/1033/jquery.js"></script>
<script type="text/javascript" src="/_layouts/1033/ui.core.js"></script>
<script type="text/javascript" src="/_layouts/1033/jquery-ui-1.7.3.custom.js
"></script>
<script type="text/javascript" src="JS.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#test').click(function() {
$.blockUI({ message: $('#question'), css: { width: '275px' } });
});
$('#yes').click(function() {
// update the block message
$.blockUI({ message: "<h1>Remote call in progress...</h1>" });
$.ajax({
url: 'wait.php',
cache: false,
complete: function() {
// unblock when remote call returns
$.unblockUI();
}
});
});
$('#no').click(function() {
$.unblockUI();
return false;
});
});
</script>
<hr />
</asp:Content>
Its a jquery plugin I downloaded from here,
Jquery Plugin I am using
because you are using
<input id="test" type="submit" value="Show Dialog" />
which cause postback due to which dialog disappear try
<input id="test" type="button" value="Show Dialog" />
your button #test is a submit button, that needs to prevent submitting to form if you want to see the message
try
$('#test').click(function(e) {
e.preventDefault();
$.blockUI({ message: $('#question'), css: { width: '275px' } });
});
Try this code, I hope it will work:
$('#your form name').submit(function() {
$.blockUI({ message: $('#question'), css: { width: '275px' } });
});

Can't pass variable from JQuery AJAX to C# code behind

Not sure what I'm doing wrong but I can't get my JQuery AJAX call to pass the variable properly. It recieves it just fine. I'm probably overlooking something minor. Thanks.
(Also, is there any way to pass data this way without using a [WebMethod] or via the URL?)
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<script src="Scripts/jquery-1.7.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$('#button').click(function(){
var json_obj = "{'" + $('#t1').val() + "' : '" + $('#p1').val() + "', '" + $('#t2').val() + "' : '" + $('#p2').val() + "'}";
$.ajax({
type: "POST",
url: 'Default.aspx/test',
contentType: 'application/json; charset=utf-8',
data: "thisisatest",//json_obj,
dataType: 'json',
success: function(msg) {
//$('#result').html(msg.d);
alert(msg.d)
},
error: function(msg) {
//$('#result').html(msg.d);
alert(msg.d + " err")
}
});
});
});
</script>
</head>
<body>
<div>
Type: 1: <input type="text" id="t1" />
Property 1: <input type="text" id="p1" />
<br /><br />
Type 2: <input type="text" id="t2" />
Property 2: <input type="text" id="p2" />
<input type="button" value="Add object!" id="button" />
<br /><br />
<div id="result"></div>
</div>
</body>
</html>
Code Behind
[WebMethod]
public string test(string json)
{
return json;
}
Here's a full example I wrote for you to illustrate the concept:
<%# Page Language="C#" %>
<%# Import Namespace="System.Web.Services" %>
<script type="text/C#" runat="server">
public class MyModel
{
public string T1 { get; set; }
public string P1 { get; set; }
public string T2 { get; set; }
public string P2 { get; set; }
}
[WebMethod]
public static string Test(MyModel obj)
{
return "Hello from test";
}
</script>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
Type: 1: <input type="text" id="t1" />
Property 1: <input type="text" id="p1" />
<br /><br />
Type 2: <input type="text" id="t2" />
Property 2: <input type="text" id="p2" />
<input type="button" value="Add object!" id="button" />
<br /><br />
<div id="result"></div>
<script src="scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
$('#button').click(function () {
var data = JSON.stringify({
obj: {
t1: $('#t1').val(),
p1: $('#p1').val(),
t2: $('#t2').val(),
p2: $('#p2').val()
}
});
$.ajax({
url: 'default.aspx/test',
type: 'POST',
contentType: 'application/json',
data: data,
success: function(result) {
$('#result').html(result.d);
}
});
return false;
});
</script>
</body>
</html>
I have mixed here the code behind and the markup in the same Default.aspx file but obviously you could have them separate if you prefer.
WebMethods must be static!
http://encosia.com/why-do-aspnet-ajax-page-methods-have-to-be-static/
[WebMethod]
public static string test(string json)
{
return json;
}
and your JSON input should be :
var jsonInput = { 'json': 'XXXXXXX'};
where 'json' is equal to the name of the webmethod parameter
and in the Ajax function
data:JSON.stringify(jsonInput)
You can change the method to GET and append the value to the URL like so...
$.ajax({
type: "GET",
url: 'Default.aspx/test?json=' + 'thisisatest',
contentType: 'application/json; charset=utf-8',
success: function(msg) {
//$('#result').html(msg.d);
alert(msg.d)
},
error: function(msg) {
//$('#result').html(msg.d);
alert(msg.d + " err")
}
});
Then in your code behind....
protected void Page_Load(object sender, EventArgs e)
{
Response.ContentType = "application/json; charset=utf-8";
Response.Write(Request["json"]);
}
If You're going to go this route though, I'd recommend not using Code Behinds as they have to process the entire ASP.NET Web Forms Page Life Cycle. You're better of using ASP.NET Handlers (ashx).
Good luck!

Categories

Resources