Fetching Cities dynamically in Asp.net HTML control - c#

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

Related

How to call codebehind method from Jquery after autocomplete selection

I have a autocomplete text box as and when the user types the city names are prompted. Once the user selects city name the selected value is retrieved using the following code:
$(document).ready(function() {
$('#txtName').on('change', function() {
$('#selectedItem').html('You selected: ' + this.value);
}).change();
$('#txtName').on('autocompleteselect', function(e, ui) {
$('#selectedItem').html('You selected: ' + ui.item.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Now I need to pass the selected value and call method in aspx.cs (code-behind) to retrieve further details of selected city.
How can I call a method from JQuery can somebody guide me towards that
You must call ajax in autocompleteselect like this
$('#txtName').on('autocompleteselect', function (e, ui) {
$('#selectedItem').html('You selected: ' + ui.item.value);
$.ajax({url: "aspx.cs",data:{value:ui.item.value}, success: function(result){
//response from server
}});
});
Server Side changes
You need to mark that method with WebMethod attribute to call it from the client side or you need to create a web service.
[WebMethod]
public static yourObject GetCityDetails(string cityId)//name this method as per your needs.
{
//Do whatever you want.
return yourObject; //it can also be in JSON format.
}
Client Side changes
Make an ajax call to the method from the client side.
$('#txtName').on('autocompleteselect', function(e, ui) {
$('#selectedItem').html('You selected: ' + ui.item.value);
$.ajax({
url: "yourpage.aspx/GetCityDetails", //same method name here.
data: { cityId: this.value },
success: function(result) {
//do whatever you want with server side data here.
}
});
});
You Can use Web Method
function GetDetails(cityId) {
$.ajax({
type: "POST",
url: 'Default.aspx/GetDetails',
data: {"cityId":cityId},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
console.log(msg);
},
error: function (e) {
console.log(e);
}
});
}
$(document).ready(function() {
$('#txtName').on('change', function() {
$('#selectedItem').html('You selected: ' + this.value);
}).change();
$('#txtName').on('autocompleteselect', function(e, ui) {
$('#selectedItem').html('You selected: ' + ui.item.value);
GetDetails(ui.item.value);
});
in your aspx page
[WebMethod] //Default.aspx.cs
public static void GetDetails(cityId)
{
//Your Logic
}
Use $.Ajax to send the selected value to the server (code-behind) and get the response:
$('#txtName').on('autocompleteselect', function(e, ui) {
$('#selectedItem').html('You selected: ' + ui.item.value);
$.ajax({
url: "your-page.aspx/GetCityDetails",
data: { Name: this.value },
success: function(result) {
//Process the result from the code-behind.
}
});
});
Your code-behind must have a webmethod named GetCityDetails that accepts the name parameter and returns a city object as JSON.
This is what solved my issue:
The following is the code in jquery part in .aspx
function SetCityName(cityName) {
$.ajax({
type: "POST",
url: 'Default.aspx/GetCityDetails',
data: JSON.stringify({ cityName: cityName }),
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("CityName:" + cityName + "\n\nRequest: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (result) {
alert("We returned: " + result.d);
}
});
}
This is the code in .aspx.cs
[WebMethod]
public static string GetCityDetails(string cityName)
{
MessageBox.Show(cityName);
return "success";
}
The trick part is using the following piece in JQuery. I have tried above alternatives provided but none worked apart from the below piece of code:
data: JSON.stringify({ cityName: cityName }),

JQuery Autocomplete on .NetCore 2 MVC

I'm working on an autocomplete that calls a method on my home controller, the javascript calls the method and returns the array. However the values do not display on the text box drop down, nothing does.
If I use a straight array as the source and don't call the home controller then it works just fine.
I don't see what I'm missing here, so I narrowed down the home controller method just to return an array using no logic until I figure this problem out.
Home Controller Method:
public string[] GetPatientName()
{
var names = new List<string> { "Bent","Boon","Book", "Al", "Cat", "Doe", "Ed", "Fox", "George" };
return names.ToArray();
}
Javascript:
<script language="javascript" type="text/javascript">
$(function() {
$('#tags').autocomplete({
source: function(request, response) {
$.ajax({
url: "/Home/GetPatientName",
data: "{ 'pre':'" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function(data) {
response($.map(data.d,
function (item) {
alert(item);
return { value: item }
}));
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
delay: 0
});
});
</script>
HTML
<form>
<input id="tags" type="text" />
</form>
2 things:
1. From the top of my mind, if it wirked with a regular array and didnt work with the result of jQuery map function you probably need to ad .get() in order to get a clean array. To be precise
$.map(data.d,function (item) {
alert(item);
return { value: item }
}).get();
2. If that doesnt work, you would really have to share more data like what is the "response" function and exactly what response you are getting from the server (you could get that from the web browser's dev tools)

Adding an asp.net custom user control from JQuery

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

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 !!

Ajax Autocomplete using jQuery

I have the following code to retrieve departments names from db I have problem formatting CSS of data like background and font color
<script type="text/jscript">
$(document).ready(function() {
$.ajax({
type: "POST",
url: "/AjaxLoad.asmx/GetBrands",
dataType: "json",
data: "{}",
contentType: "application/json; charset=utf-8",
success: function(data) {
var datafromServer = data.d.split(":");
$("[id$='tbBrands']").autocomplete({
source: datafromServer
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
}
</script>
<div id="ajaxbrands">
<input id="tbBrands" runat="server" />
</div>
Any idea how to add text, like <p > or <div> to each list item?
I can think on 2 options:
1.Add it in your php code (like rdlowrey aadvised),
for instance:
$query = mysql_query("SELECT * FROM brands");
while($brand = mysql_fetch_array($query))
{
echo "<p>".$brand['name']."</p>";
}
2.Use jquery to do it.
"Split" converts your string to an array of sub-strings.
You should edit the autocomplete function so it will add each sub-string the desirable code. Add the function's code for more help.
Well, i assume you are using .NET, so, i wont mess around with server side code.
You can add this to your success callback function:
success: function(data) {
var datafromServer = data.d.split(":");
for(var item in datafromServer){
datafromServer[item] = '<p class="whatever">' + datafromServer[item] + '</p>';
}
$("[id$='tbBrands']").autocomplete({
source: datafromServer
});
},
The for loop added will surround every item in the array, with a p, or div, or whatever.

Categories

Resources