Adding an asp.net custom user control from JQuery - c#

I am using following JQuery code from somewhere on the internet to load content on browser window scroll.
var pageIndex = 1;
var pageCount;
$(window).scroll(function () {
if ($(window).scrollTop() == $(document).height() - $(window).height()) {
GetRecords();
}
});
function GetRecords() {
pageIndex++;
if (pageIndex == 2 || pageIndex <= pageCount) {
$("#loader").show();
$.ajax({
type: "POST",
url: "CS.aspx/GetCustomers",
data: '{pageIndex: ' + pageIndex + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
}
});
}
}
function OnSuccess(response) {
var xmlDoc = $.parseXML(response.d);
var xml = $(xmlDoc);
pageCount = parseInt(xml.find("PageCount").eq(0).find("PageCount").text());
var customers = xml.find("Customers");
customers.each(function () {
var customer = $(this);
var table = $("#dvCustomers table").eq(0).clone(true);
$(".name", table).html(customer.find("ContactName").text());
$(".city", table).html(customer.find("City").text());
$(".postal", table).html(customer.find("PostalCode").text());
$(".country", table).html(customer.find("Country").text());
$(".phone", table).html(customer.find("Phone").text());
$(".fax", table).html(customer.find("Fax").text());
$("#dvCustomers").append(table).append("<br />");
});
$("#loader").hide();
}
As you can see its adding HTML table on response success. But I have an asp.net user-control that I want to add instead of this HTML table when content scrolls (In short I want to add a server side control from JQuery). I can't add user-control's HTML in place of this HTML table because its code is too lengthy and complex and I don't know much JQuery. I am the beginner of the beginner concept of JQuery. Moreover I am a specialist in back-end programming. So, I can't code that business logic in JQuery. So any one please help me in doing so.

Like kintaro alerady suggested; render you html on server side (in a user control) and then load that control inside web method to return results in HTML to client side.
Here'a an example:
JavaScript code:
var pageIndex = 0;
var data = { "pageIndex": pageIndex };
$.ajax({
type: "POST",
url: "CS.aspx/GetCustomers",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8"
}).done(function (result) {
$("#dvCustomers").append(result.d);
});
and the PageMethod on server side:
[WebMethod]
public static string GetCustomers(int pageIndex)
{
Page pageHolder = new Page();
UserControl viewControl = (UserControl)pageHolder.LoadControl("_path_to_customers_usercontrol");
pageHolder.Controls.Add(viewControl);
StringWriter output = new StringWriter();
HttpContext.Current.Server.Execute(pageHolder, output, false);
return output.ToString();
}
You will also have to pass a pageIndex value to Customers user controls, you can to that by casting the result of LoadControl method to a class that represnts your customer user control and then set PageIndex property.
If you are developing your project as ASP.NET Web Site you'll have to use reflection to set property value. Here's an example:
Type viewControlType = viewControl.GetType();
PropertyInfo field = viewControlType.GetProperty("PageIndex");
if (field != null)
{
field.SetValue(viewControl, pageIndex, null);
}

You can switch the HTML of the control with url parameter:
$.ajax({
type: "POST",
url: "CS.aspx/GetCustomers",
data: '{pageIndex: ' + pageIndex + ', ajaxcall: true}',
contentType: "application/json; charset=utf-8",
dataType: "json"
}).done(function (data) {
$("#dvCustomers table").append(data);
});
And in the ascx control:
<%if (Page.Request.QueryString.Get("ajaxcall") == "true")
{%>
normal html control render.
<%}
else
{%>
<tr>
<td>All data of table only tr an tds</td>
</tr>
<%} %>

Create a div and put your user control in this div. then set the visibility:hidden and once it is success display it(set visibility to visible using jquery) :
<div style="visibility:hidden" id="dv1">
<uc1:usercontrol Visible="true" runat="server">...
</div>
Jquery :
$("#dv1").css("visibility","visible");

Related

display only first 10 records from array using c# jquery

Index.aspx
$(document).ready(function () {
$.ajax({
type: "POST",
url: "Index.aspx/GetData",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (msg) {
$.each(msg.d, function (index, value) {
$('#myDiv').html(value.Email);
});
}
})
return false;
});
Index.aspx.cs
[WebMethod]
public static IEnumerable<TemperatureEntity> GetData()
{
//return array data
I have traverse through array and want to display it in tabular format on html like email,phonenumber.
If you want to do it exaclty on the client side then check the slice() jQuery function
You should modify your code as following:
var slicedData = msg.d.slice(0, 10);
$.each(slicedData, function (index, value) {
var html = $('#myDiv').html();
html += value.Email;
html += value.PhoneNumber;
$('#myDiv').html(html + '<br />');
});
But if you can modify the resulting array on the server side - do it on server side with Linq method Take(10);

Fetching Cities dynamically in Asp.net HTML control

I have a HTML dropdown list for countries. Now I want to populate the City dropdown accordingly using ajax
<select class="form-control" id="ddCountry" runat="server" tabindex="8"></select>
<select class="form-control" id="ddCity" runat="server" tabindex="9"></select>
<script type="text/javascript">
$('#ddCountry').on('change', function () {
var storeData = { countryId: this.value }
$.ajax({
type: "POST",
url: "UserRegistration.aspx/GetCities",
data: JSON.stringify(storeData),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("The data in list is "+data);
},
error: error
});
});
</script>
My method on .cs page is as follows:
[WebMethod]
public static List<CityBO> GetCities(string countryId)
{
//returning cities
}
The problem is I am able to fetch the data in GetCities method but not able to show it in the ddCity list because it is a HTML control and the method is static, so
ddCity.Items.AddRange(list_of_countries) is not working as ddCity is not being recognized in static method. Please tell how to fill the dropdown list.
You cannot access controls in static method. You need to return list of cities from webmethod and fill dropdown using javascript.In success method of ajax write code like this.
success: function (data) {
fillDropDown(data.d);
}
function fillDropDown(data){
var html = "";
for (var i = 0; i < data.length; i++)
{
html += "<option value='" + data[i].ValueField+ "'>" +
data[i].TextField+ "</option>";
}
$("select[id$=ddlCity]").html(html);
}
You can use ajax success function given below.
success: function (data)
{
var lankanListArray = JSON.parse(data.d);
// running a loop
$.each(lankanListArray, function (index, value)
{
$("#ddlCity").append($("<option></option>").val(this.name).html(this.value));
});
}

Getting value from a dropdown list that was populated with AJAX

I had populated an ASP.net dropdown list with AJAX now I need to get the Id to store in into the database in a C# method, (I'm using LINQ)
This is my webmethod
[WebMethod]
public static ArrayList GetLanguageList()
{
ArrayList lstArrLanguage = new ArrayList();
IQueryable<Common.Town> myList = new SupplierBL().GetTowns();
foreach(Common.Town t in myList)
{
string name = t.Name;
string id = t.TownId.ToString();
lstArrLanguage.Add(new ListItem(name, id));
}
return lstArrLanguage;
}
My test.aspx code
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
url: "test.aspx/GetLanguageList",
data: '',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#ddlLanguage").empty().append($("<option></option>").val("[-]").html("Please select"));
$.each(msg.d, function () {
$('#<%=ddlLanguage.ClientID%>').append($("<option></option>").val(this['Value']).html(this['Text']));
});
},
error: function () {
alert("An error has occurred during processing your request.");
}
});
});
</script>
You can't get selected value from DropDownList if you adding options in javaScript. You can try the following
string selectedValue = Request.Form[ddlLanguage.UniqueID];
This question may be useful also.
If you populate the value of dropdown via ajax than it can't be available on Server Side because the page doesn't postback during ajax request.
In order to get the value of dropdown in C# use below snippets :
String _value = Convert.ToString(Request[ddlLanguage.ClientID]);
Hope this will help !!

C# webservice calls using jQuery 1.7.1 /eval/seq/

So here's the problem. I have three pages that make web service calls. The first time I land on the page and make the call it works fine, however if I switch to the second page it tries to make a web service call to the wrong service. Here's some info:
pages:
Page1.aspx - has Page1.js
Page2.aspx - has Page2.js
js files:
Page1.js
var filterCriteria = "";
function GetList() {
$.ajax({
type: "POST",
url: "/webServices/Page1.asmx/Page1List",
contentType: "application/json; charset=utf-8",
data: "{'letter':'" + filterCriteria + "'}",
dataType: "json",
success: function (result) {
DisplayList(result.d);
}
});
}
function GetSearchResults() {
$.ajax({
type: "POST",
url: "/webServices/Page1.asmx/Page1FilteredList",
contentType: "application/json; charset=utf-8",
data: "{'searchCriteria':'" + $("#Search").val() + "'}",
dataType: "json",
success: function (result) {
DisplayList(result.d);
}
});
}
function DisplayList(object) {
var html = '';
for (var i = 0; i < object.length; i++) {
//format results and append
}
if (object.length == 0) {
html += "<li class=\"filteredList\" style=\"padding: 10px;\">No Results Found</li>";
}
$("#Page1List").html(html);
}
Page2.js
var filterCriteria = "";
function GetList() {
$.ajax({
type: "POST",
url: "/webServices/Page2.asmx/Page2List",
contentType: "application/json; charset=utf-8",
data: "{'letter':'" + filterCriteria + "'}",
dataType: "json",
success: function (result) {
DisplayList(result.d);
}
});
}
function GetSearchResults() {
$.ajax({
type: "POST",
url: "/webServices/Page2.asmx/Page2FilteredList",
contentType: "application/json; charset=utf-8",
data: "{'searchCriteria':'" + $("#Search").val() + "'}",
dataType: "json",
success: function (result) {
DisplayList(result.d);
}
});
}
function DisplayList(object) {
var html = '';
for (var i = 0; i < object.length; i++) {
//format results and append
}
if (object.length == 0) {
html += "<li class=\"filteredList\" style=\"padding: 10px;\">No Results Found</li>";
}
$("#Page2List").html(html);
}
So both have the same calls and the same information and the only real difference is that the results are different and they make a web service call to different web services that get different data.
Now each time that I switch between I get a new js file which is
jQuery-1.7.1.min.js/eval/seq/1
jQuery-1.7.1.min.js/eval/seq/2
jQuery-1.7.1.min.js/eval/seq/3
jQuery-1.7.1.min.js/eval/seq/4
depending on how many times I switch back an forth. Is there any way to stop the eval or is there something in my code that is causing the jQuery to store evals of the code I am using and what can I do to resolve it?
So the problem was that I was loading page transitions from jquery mobile. What was happening was that jquery mobile appends new page data to the DOM instead of forcing a page load. This was causing both javascript files to be loaded simultaneously meaning that which ever js file was loaded last was the primary and because both js files were calling functions with the same name it would load them multiple times.
Resolution
remove the $.mobile.load() event and force the click event to append the pathname to the url
$("#GoPage1").on("click", function () { window.location = "/dir/Page1.aspx"; });
$("#GoPage2").on("click", function () { window.location = "/dir/Page2.aspx"; });

Jquery AJAX with ASP.NET WebMethod refreshing the entire page

I am using Jquery Ajax to set the values of a Label and a ListBox in my form. I realize that values are set properly by the function. But just after that , the page just refreshes clearing all previously set values . Why is this happening ? Iam new to Jquery/Ajax. Am I missing any fundamentals here ? Thanks in Advance.
Iam pasting the entire code
$(document).ready(function () {
$('#Button1').bind('click', function clk() {
$.ajax({
type: "POST",
url: "WebForm5.aspx/TestMethod",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert(result.d.ListBox.length);
for (var i = 0; i < result.d.ListBox.length; i++) {
alert(result.d.ListBox[i]);
$(document.createElement("option")).attr("value", result.d.ListBox[i]).html(result.d.ListBox[i])
.appendTo('#<%=ListBox1.ClientID %>');
$('#Label1').text(result.d.MyProperty);
}
}
});
})
});
Button1 in your code is an asp button which is a submit button. When you click on it, it will submit the page and refresh the whole page. If you want to stop the page from being submitted on button click return false, it will work.
$('#Button1').bind('click', function clk() {
$.ajax({
type: "POST",
url: "WebForm5.aspx/TestMethod",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert(result.d.ListBox.length);
for (var i = 0; i < result.d.ListBox.length; i++) {
alert(result.d.ListBox[i]);
$(document.createElement("option")).attr("value", result.d.ListBox[i]).html(result.d.ListBox[i])
.appendTo('#<%=ListBox1.ClientID %>');
$('#Label1').text(result.d.MyProperty);
}
}
});
return false;
})

Categories

Resources