How to fill a DropDown using Jquery Ajax Call? - c#

I have a WebMethod which gets data that I want to fill DropDown with in a DataSet.
Currently I am filling the dropdown using a hardcoded object. But I want to replace this hard coded object with data returned by webmethod.
[System.Web.Services.WebMethod]
public static string GetDropDownDataWM(string name)
{
//return "Hello " + name + Environment.NewLine + "The Current Time is: "
// + DateTime.Now.ToString();
var msg = "arbaaz";
string[] name1 = new string[1];
string[] Value = new string[1];
name1[0] = "#Empcode";
Value[0] = HttpContext.Current.Session["LoginUser"].ToString().Trim();
DataSet ds = new DataSet();
dboperation dbo = new dboperation();
ds = dbo.executeProcedure("GetDropDownsForVendor", name1, Value, 1);
return ds.GetXml();
}
CLIENT SIDE(UPDATE 1):
<script type = "text/javascript">
function GetDropDownData() {
var myDropDownList = $('.myDropDownLisTId');
$.ajax({
type: "POST",
url: "test.aspx/GetDropDownDataWM",
data: '{name: "abc" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$.each(jQuery.parseJSON(data.d), function () {
myDropDownList.append($("<option></option>").val(this['FieldDescription']).html(this['FieldCode']));
});
},
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
console.log(response.d);
alert(response.d);
}
</script>

function GetDropDownData() {
$.ajax({
type: "POST",
url: "test.aspx/GetDropDownDataWM",
data: '{name: "abc" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data.d)
{
$.each(data.d, function (){
$(".myDropDownLisTId").append($("<option />").val(this.KeyName).text(this.ValueName));
});
},
failure: function () {
alert("Failed!");
}
});
}

var theDropDown = document.getElementById("myDropDownLisTId");
theDropDown.length = 0;
$.each(items, function (key, value) {
$("#myDropDownLisTId").append($("<option></option>").val(value.PKId).html(value.SubDesc));
here "SubDesc",PKId describes the value getting out of Database., u need to separate your value from dataset.

From the WebMethod, don't send DataSet directly, send XML...
[System.Web.Services.WebMethod]
public static string GetDropDownDataWM(string name)
{
DataSet ds = new DataSet();
ds.Tables.Add("Table0");
ds.Tables[0].Columns.Add("OptionValue");
ds.Tables[0].Columns.Add("OptionText");
ds.Tables[0].Rows.Add("0", "test 0");
ds.Tables[0].Rows.Add("1", "test 1");
ds.Tables[0].Rows.Add("2", "test 2");
ds.Tables[0].Rows.Add("3", "test 3");
ds.Tables[0].Rows.Add("4", "test 4");
return ds.GetXml();
}
Before Ajax call...
var myDropDownList = $('.myDropDownLisTId');
Try like below...(inside Ajax call)
success: function (response) {
debugger;
$(response.d).find('Table0').each(function () {
var OptionValue = $(this).find('OptionValue').text();
var OptionText = $(this).find('OptionText').text();
var option = $("<option>" + OptionText + "</option>");
option.attr("value", OptionValue);
myDropDownList.append(option);
});
},
Note:
OptionValue and OptionText are the Columns of DataSet Table.
$(response.d).find('Table0').each(function (){}) - Here Table0
is the name of Table inside DataSet.

[System.Web.Services.WebMethod]
public static string GetDropDownDataWM(string name)
{
//return "Hello " + name + Environment.NewLine + "The Current Time is: "
// + DateTime.Now.ToString();
var msg = "arbaaz";
string[] name1 = new string[1];
string[] Value = new string[1];
name1[0] = "#Empcode";
Value[0] = HttpContext.Current.Session["LoginUser"].ToString().Trim();
DataSet ds = new DataSet();
dboperation dbo = new dboperation();
ds = dbo.executeProcedure("GetDropDownsForVendor", name1, Value, 1);
return DataSetToJSON(ds);
}
public static string DataSetToJSON(DataSet ds)
{
Dictionary<string, object> dict = new Dictionary<string, object>();
foreach (DataTable dt in ds.Tables)
{
object[] arr = new object[dt.Rows.Count + 1];
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
arr[i] = dt.Rows[i].ItemArray;
}
dict.Add(dt.TableName, arr);
}
var lstJson = Newtonsoft.Json.JsonConvert.SerializeObject(dict);
return lstJson;
}
Ajax Call
function GetAssociation() {
var myDropDownList = $("#myDropDownLisTId");
var post_data = JSON.stringify({ "name": "xyz"});
$.ajax({
type: "POST",
url: "test.aspx/GetDropDownDataWM",
data: post_data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
json_data = JSON.parse(response.d);
myDropDownList.empty();
for(i=0; i<json_data.Table.length; i++)
{
myDropDownList.append($("<option></option>").val(json_data.Table[i][0]).html(json_data.Table[i][1]));
}
},
failure: function (response) {
alert(response.d);
}
});
}

// We can bind dropdown list using this Jquery function in JS script
function listDropdownBind() {
var requestId = 123;
$.ajax({
type: "POST",
url: "/api/ControllerName/ActionName?param=" + param, // call API with parameter
headers: { 'rId': requestId },
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
var optionhtml1 = '';
var optionhtml1 = '<option value="' +
0 + '">' + "--Select--" + '</option>';
$("#ddlName").append(optionhtml1);
$.each(data, function (i) {
var optionhtml = '<option value="' +
data.d[i].Value + '">' + data.d[i].Text + '</option>';
$("#ddlName").append(optionhtml);
});
}
});
};

Related

Jquery UI Modal Dialog Not Working Properly

I created a jQuery modal password dialog box to redirect to a page for password validation.
The modal dialog appears alright, but instead of executing the method that handles the password validation it instead shows the error [object Object] on a the browsers alert dialog. I'm trying to figure out what I'm doing wrong here.
Below is my code:
JavaScript/jQuery
$(document).on("click", "[id*=lnkView1]", function() {
$("#dlgPassword").dialog({
title: "View Details",
buttons: {
Go: function() {
var valPassword = $("[id*=cpgnPassword]").val();
var hdfCamId = $('#<%=rptCampaigns.ClientID %>').find('input:hidden[id$="hdfCampaignID"]').val();
$("[id*=hdfCampaignID2]").val(hdfCamId);
//var jsonObj = '{password: "' + valPassword + '"}';
var res;
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: '{password: "' + valPassword + '"}',
dataType: 'json',
url: 'CampaignsList.aspx/ValidatePasswordWM',
success: function(data) {
alert('successful')
},
error: function(err) {
alert(err.toString());
}
});
$(this).dialog('close');
}
},
modal: true
});
return false;
});
Code-Behind
protected void ValidatePassword(object password)
{
var campaign = new CampaignsService().GetByCampaignId(hdfCampaignID2.Value);
if (campaign != null)
{
if (campaign.Password.Equals(password))
Response.Redirect("CampaignDetails.aspx?CampaignID=" + hdfCampaignID2.Value);
}
}
[WebMethod]
public static void ValidatePasswordWM(object password)
{
CampaignsList page = new CampaignsList();
page.ValidatePassword(password);
}
Can someone help me figure out what's wrong?
You need the appendTo property on your dialog so it gets added to the form properly.
$("#dlgPassword").dialog({
title: "View Details",
appendTo: "form",
buttons: {
...
Instead of err.toString(), try err.message
This code shows a products cadastre at jQuery UI. When OK button pressed, re-populate dropdownlist.
Javascript:
$dialog = $("#dlgCadastroProduto").dialog({
modal: true,
autoOpen: false,
height: 500,
width: 700,
buttons: {
Ok: function () {
$(this).dialog("close");
$("#lstProducts").empty();
$("#lstSelectedProducts").empty();
$.ajax({
type: "GET",
url: '/Produto/jsonLoad',
async: true,
dataType: 'json',
success:
function (data) {
//alert('sucesso');
$.each(data, function (index, value) {
//insere elemento na droplist
$("#lstProducts").append('<option value='+value.ID+'>'+value.Descricao+'</option>')
});
},
error: function (data) {
//alert(data);
}
});
}
}
});
$("#btnCadastroProduto").button().on("click", function () {
$dialog.dialog("open");
});
Code-Behind at Controller:
public JsonResult jsonLoad()
{
var lista = _produtoBLL.FindAll();
var xpto = lista.Select(x => new { Id = x.ID, Descricao = x.Descricao });
return Json(xpto, JsonRequestBehavior.AllowGet);
}
I hope i have helped
This is just sample code you can you with yours
Client Side
var mparam = "{param1:'" + mvar1 + "',param_n:'" + mvar_n + "'}";
$.ajax({
type: "POST",
url: "file_name.aspx/web_method",
data: mparam,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (Response) {
try {
var msdata = JSON.parse(Response.d);
if (msdata.err == "0") {
location.replace("newlocation");
}else{
alert("Error:" + msdata.msg);
}
} catch (e) {
alert("Error in JSON parser error:" + e.description);
}
},
error: function (medata) {
alert("Internal Server Error:" + medata);
}
});
Server Side
[System.Web.Services.WebMethod]
public static string web_method(string param1, string param_n)
{
string strerror = "0", strmessage = "";
try
{
strerror = "0";
}
catch (Exception ex)
{
strerror = "2";
strmessage = ex.Message;
}
return "{\"err\":\"" + strerror + "\",\"msg\":\"" + strmessage + "\"}";
}

ajax call serialize and deserialize data

I have the following ajax call:
$(document).ready(function() {
$.ajax({
type: "POST",
url: "/LoadCount.aspx/GetCounts",
contentType: "application/json; charset=utf-8",
data: "",
async: false,
dataType: "json",
success: function(data) {
var myObj = JSON.parse(data.d);
alert(myObj.length);
for (var i = 0; i < myObj.length; i++) {
alert(myObj[0]);
}
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
});
I am getting undefined when I alert the length
Here's my Method in my LoadCount.aspx
[WebMethod]
public static string ObtenerContador()
{
List<MenuItem> menu =(List<MenuItem>)HttpContext.Current.Session["MenuItems"];
Dictionary<string, int> dic = new Dictionary<string, int>();
foreach (MenuItemAMostrar item in menu)
{
dic.Add(item.ControlID,1);
};
return new JavaScriptSerializer().Serialize(dic); //or any other suggested serialization method
}
this is what I am getting in the success function:
{"MenuCLESAAsignar":1,"MenuOCGestores":1,"MenuOcAAutorizar":1,"MenuOcAAutorizarBanco":1,"MenuOCGestoresObservadas":1,"MenuCLESActivos":1,"MenuParametros":1,"MenuCLESConAddendaAAprobarSup":1,"MenuPendienteAprobacion":1,"MenuConsultaCLES":1}
The question is, how do I deserialize that dictionary in my ajax success function?
Once deserialized, how do I populate it, obtaining the data?
thanks!
As somebody else mentioned, you just use JSON.parse() to parse the data.
From there it just creates an object, and you can access the data with ..
Like so:
http://jsfiddle.net/SJGLF/1/
var myData = JSON.parse(jsonData);
for(var i in myData)
{
console.log(i + " = " + myData[i]);
}
Are you looking for this?
success: function (data)
{
var myObj = JSON.parse(data.d);
},

reading a string table jquery ajax success function

the code:
[WebMethod]
public static string [] GetMorechatMsgs(int toclient, int fromclient, int top)
{
string [] List =new string[2];
int chatcount = new ChatPage().GetAllMsgCount(toclient, fromclient);
if (top <= chatcount)
{
string toreturn=new ChatPage().GetChat(fromclient, toclient, "", top);
List[0]= toreturn;
List[1] = chatcount.ToString();
}
else {
List = null;
}
return List;
}
html:
$.ajax({
type: "POST",
url: "ChatPage.aspx/GetMorechatMsgs",
data: "{'toclient':'" + ToClient + "','fromclient': '" + fromClient + "','top': '" + $("#MsgCount").val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.d != "") {
// how to read the returned table
}
else {
}
},
error: function (xhr) {
alert("responseText: " + xhr.responseText);
}
});
How can i read the returned string array on success ?
serialize the list of your string i.e
change your method to this:
[WebMethod]
public static string GetMorechatMsgs(int toclient, int fromclient, int top)
{
/// your usual code
return new JavaScriptSerializer().Serialze(list);
}
and read returned data like this:
success: function (data) {
var jsonData =$.parseJSON(data.d);
for(var i=0; i<jsonData.length; i++){
console.log(jsonData[i]);
}
}
The WebMethod will return your string array in the form ["string", "string", "string", ...], therefore, simply loop through the array in the way Manish demonstrated:
success: function (data) {
var jsonData =$.parseJSON(data.d);
for(var i=0; i<jsonData.length; i++){
var theString = jsonData[i];
//Do something with the string
}
}

Two Listboxes with same value, I need to remove identicial value from one Listbox

I have two ASP ListBoxes. As you can see below, lbAvailable is populated on PageLoad with WebMethod and populates all cities. LbChoosen is populated depending on DropDown Value Chosen. The Dropdown has 4 options(ALL, Top25, Top50, Top100). for example if you choose Top 25 which is value 4, lbChosen populates top 25 cities (This all works).
MY PROBLEM IS lbAvaliable always populates all cities. So if i chose top 25 which populates top25 cities into lbChoosen, how can those value (top25 cities) be removed from lbAvailable
function LoadMarketsAvailableJS() {
var ddlFootprint = $('#ddlFootprint');
var lbChoosen = $('#lbChoosen');
var lbAvailable = $('#lbAvailable');
lbChoosen.empty();
var SelectedMarkets = [];
var url = "";
//Load lbAvailable on Page Load with all Markets
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Campaign.aspx/LoadAvailableMarkets",
dataType: "json",
success: function (msg) {
var obj = $.parseJSON(msg.d);
for (var i = 0; i < obj.Markets.length; i++) {
if (SelectedMarkets.indexOf(obj.Markets[i].id.toString()) == -1) {
$("#lbAvailable").append($("<option></option>")
.attr("value", obj.Markets[i].id)
.text(obj.Markets[i].name + " - " + obj.Markets[i].rank));
}
}
},
error: function(result) {
alert("Error");
}
});
//Check DropdownList
if (parseInt(ddlFootprint.val()) == 1) {
url = 'Campaign.aspx/LoadAvailableMarkets';
} else if (parseInt(ddlFootprint.val()) == 2) {
url = 'Campaign.aspx/LoadTop100Markets';
}
else if (parseInt(ddlFootprint.val()) == 3) {
url = 'Campaign.aspx/LoadTop50Markets';
}
else if (parseInt(ddlFootprint.val()) == 4) {
url = 'Campaign.aspx/LoadTop25Markets';
}
else if (parseInt(ddlFootprint.val()) == 5) {
url = 'Campaign.aspx/LoadAvailableMarkets';
}
//Load Select Dropdown Value to lbChoosen
if (url.length > 0) {
$.ajax({
type: "POST",
url: url,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var obj = $.parseJSON(msg.d);
for (var i = 0; i < obj.Markets.length; i++) {
if (SelectedMarkets.indexOf(obj.Markets[i].id.toString()) == -1) {
lbChoosen
.append($("<option></option>")
.attr("value", obj.Markets[i].id)
.text(obj.Markets[i].name + " - " + obj.Markets[i].rank));
}
}
},
error: function (jqXHR, textStatus, errorThrown) {
},
complete: function (jqXHR, textStatus) {
}
});
}
}
Assuming I've understood what you're asking, if you want to remove options from lbAvailable as they're added to lbChoosen you should be add the following line:
lbAvailable.find('option[value="' + obj.Markets[i].id + '"]').remove();
So your code will look something like:
success: function (msg) {
var obj = $.parseJSON(msg.d);
for (var i = 0; i < obj.Markets.length; i++) {
if (SelectedMarkets.indexOf(obj.Markets[i].id.toString()) == -1) {
lbChoosen
.append($("<option></option>")
.attr("value", obj.Markets[i].id)
.text(obj.Markets[i].name + " - " + obj.Markets[i].rank));
lbAvailable.find('option[value="' + obj.Markets[i].id + '"]').remove();
}
}
},

jQuery autocomplete shows undefined values while WebService is returning correct data

$(function() {
$(".tb").autocomplete({
source: function(request, response) {
$.ajax({
url: "MyService.asmx/GetCompletionList",
data: "{ 'prefixText': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function(data) { return data; },
success: function(data) {
response($.map(data.d, function(item) {
return {
value: item.Email
}
}))
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 1
});
});
This is my jQuery code and WebService method. Can any one help me?. GetCompletionList WebService method returns list of string but autocomplete on TextBox shows undefined for all values
public List<string> GetCompletionList(string prefixText)
{
RegistrationBAL _rbal = new RegistrationBAL(SessionContext.SystemUser);
DataSet ds = new DataSet();
_rbal.LoadByContextSearch(ds, prefixText);
List<string> myList = new List<string>();
foreach (DataRow row in ds.Tables[0].Rows)
{
myList.Add((string)row[0]);
}
return myList.ToList();
}
Try to change the data in the ajax call as follows
if the auto complete is done for an asp control
data: "{'prefixText':'" + document.getElementById("<%= ContactName.ClientID %>").value + "'}",
or else give as follows
data: "{'prefixText':'" + document.getElementById("requiredID").value + "'}",
edited answer where the auto complete works
function SearchText() {
$(".autosuggest").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "AutoCompleteService.asmx/GetAutoCompleteData",
data: "{'PhoneContactName':'" + document.getElementById("<%= ContactName.ClientID %>").value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
//alert("Error");
}
});
}
});
}
which resembles your ajax function but in server side I used the web service as below which the get values from the database
public class AutoCompleteService : System.Web.Services.WebService
{
[WebMethod]
public List<string> GetAutoCompleteData(string PhoneContactName)
{
List<string> result = new List<string>();
string QueryString;
QueryString = System.Configuration.ConfigurationManager.ConnectionStrings["Admin_raghuConnectionString1"].ToString();
using (SqlConnection obj_SqlConnection = new SqlConnection(QueryString))
{
using (SqlCommand obj_Sqlcommand = new SqlCommand("select DISTINCT PhoneContactName from PhoneContacts where PhoneContactName LIKE +#SearchText+'%'", obj_SqlConnection))
{
obj_SqlConnection.Open();
obj_Sqlcommand.Parameters.AddWithValue("#SearchText", PhoneContactName);
SqlDataReader obj_result = obj_Sqlcommand.ExecuteReader();
while (obj_result.Read())
{
result.Add(obj_result["PhoneContactName"].ToString().TrimEnd());
}
return result;
}
}
}
}
.. Hope this helps :D

Categories