How to dynamicallly populate selectize using c# webmethod - c#

I am using https://selectize.github.io/selectize.js/
and I've followed their example for dynamic population
in my aspx page I have
$('#stationid').selectize({
valueField: 'value',
labelField: 'text',
searchField: ['text'],
create: function (input, callback) {
$.ajax({
url: 'Search.aspx/GetListboxValues',
data: "{'query':'" + input+ "'}",
type: 'POST',
dataType: 'json',
success: function (response) {
return callback(response);
}
});
},
render: {
option: function (item, escape) {
return '<div>' + escape(item.text) + '</div>';
}
},
load: function (query, callback) {
if (!query.length) return callback();
$.ajax({
type: "POST",
url: "Search.aspx/GetListboxValues",
data: "{'query':'" + query + "'}",
contentType: "application/json; charset=utf-8",
dataType: 'json',
error: function () {
callback();
},
success: function (res) {
callback(res);
}
});
}
});
<asp:ListBox ID="stationid" Width="300" SelectionMode="Multiple" runat="server">
</asp:ListBox>
In my aspx.cs I have
[WebMethod]
public static string GetListboxValues(string query)
{
string _conString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(_conString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
string sql = "select station_name as [value], station_name as [text] from station where station_name like '%" + query + "%' group by station_name order by station_name asc";
cmd.CommandText = sql;
con.Open();
DataTable dt = new DataTable();
using (var da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
return JsonConvert.SerializeObject(dt);
}
The webmethod works and returns a json in the following format
{"d":"[{\"value\":\"I-M-987\",\"text\":\"I-M-987\"},{\"value\":\"S-2987\",\"text\":\"S-2987\"},{\"value\":\"S-987\",\"text\":\"S-987\"}]"}
If I type in the listbox then selectize adds what I'm typing and fires off the webmethod but the listbox is not populating with the returned json values. How can I solve this ? Thank you in advance!

in case anyone else has this issue, the freaking problem was the json was formatted wrong.
I needed to use eval function to get only text from json, because raw json had all those \"
so just do this
success: function (res) {
var rspns = eval(res.d);
callback(rspns);
}

Related

Failed to load WebMethod

My drop down change function works good. But the WebMethod failed to load
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("[id*=drpSub]").change(function () {
var drpSub = $("[id*=drpSub]").val();
var Gs_Id = $("[id*=ddlClass]").val();
alert(drpSub);
$.ajax({
type: 'GET',
url: 'assignments1.aspx/GetAssignmentType',
data: {},
dataType: 'json',
success: function (r) {
//var ddlCustomers = $("[id*=drpType]");
//ddlCustomers.empty().append('<option selected="selected" value="0">Please select</option>');
//$.each(r.d, function () {
// ddlCustomers.append($("<option></option>").val(this['Value']).html(this['Text']));
//});
}
});
});
});
Code Behind
[WebMethod]
public static List<ListItem> GetAssignmentType()
{
string query = "SELECT OP_AssignmentType.AT_Id, OP_AssignmentType.AT_Type + ' (' + CONVERT(varchar(10), COUNT(8)) + ')' AS AT_Type FROM OP_Assignments INNER JOIN OP_AssignmentType ON OP_Assignments.OP_AS_TypeId = OP_AssignmentType.AT_Id WHERE (OP_Assignments.OP_AS_SubjId = '" + 10 + "') AND (OP_Assignments.OP_GS_IdNo = 37) And OP_AS_LastDate>='" + DateTime.Now + "' GROUP BY OP_AssignmentType.AT_Id, OP_AssignmentType.AT_Type";
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
List<ListItem> customers = new List<ListItem>();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
customers.Add(new ListItem
{
Value = sdr["Sub_Id"].ToString(),
Text = sdr["Subject_Name"].ToString()
});
}
}
con.Close();
return customers;
}
}
}
I know code inside the web method may be wrong. My actual problem is, the page is not loading when in put break point in the web method code behind. My console is error free. Is their any fault in my jQuery. Please Help
You have to add contentType: "application/json; charset=utf-8", in your ajax so, your ajax would be like
$.ajax({
type: 'GET',
url: 'Default.aspx/GetAssignmentType',
data: {},
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (r) {
//var ddlCustomers = $("[id*=drpType]");
//ddlCustomers.empty().append('<option selected="selected" value="0">Please select</option>');
//$.each(r.d, function () {
// ddlCustomers.append($("<option></option>").val(this['Value']).html(this['Text']));
//});
}
});

How to get the value of autocomplete textbox in asp.net

Below is my code to populate an autocomplete textbox using webservice. I am fetching two database fields, once i select an item from the list related rate is displayed on an another textbox. Instead of getting the ServiceId i am getting rate field. How do i get ServiceId value please help me out. Thanking you in advance.
.aspx code
<asp:HiddenField ID="hfServiceId" runat="server" />
<asp:TextBox ID="txtTest" runat="server"></asp:TextBox>
<asp:TextBox ID="txtRate" runat="server"></asp:TextBox>
<asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="Insert"/>
my webservice code
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string[] GetServices(string prefix)
{
List<string> customers = new List<string>();
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager
.ConnectionStrings["conString"].ConnectionString;
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select ServiceName, ServiceId,Rate from Service where " +
"ServiceName like #SearchText + '%'";
cmd.Parameters.AddWithValue("#SearchText", prefix);
cmd.Connection = conn;
conn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
customers.Add(string.Format("{0}-{1}-{2}", sdr["ServiceName"], sdr["ServiceId"], sdr["Rate"]));
}
}
conn.Close();
}
return customers.ToArray();
}
}
java script code
$(function () {
$("[id$=txtTest]").autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/AutocompleteSingle.asmx/GetServices") %>',
data: "{ 'prefix': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('-')[0],
val: item.split('-')[1],
val: item.split('-')[2]
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
select: function (e, i) {
$("[id$=hfServiceId]").val(i.item.val);
$("[id$=txtRate]").val(i.item.val);
},
minLength: 1
});
});
code behind:
protected void Insert(object sender, EventArgs e)
{
string serviceId = Request.Form[hfServiceId.UniqueID]; // getting rate field value
}
Here
return {
label: item.split('-')[0],
val: item.split('-')[1],
val: item.split('-')[2]
}
you create an object with two properties with the same name, rewriting the value of the first with the value of the second. Try to name them differently.

Invoke Server Methods From Client Side Using jQuery AJAX in ASP.NET

I have to call server side method update(input parameters) by using ajax call.when I am running the code my ajax is not loading.I want to update that data to Jquery Data table.please give me suggestions
$(document).on('click', '#btnsave', function () {
//have to get the emp_id
var id = $('#hdnid').val();
update(id);
});
function update(id) {
var name = $('#txtempname').val();
var sal = $('#txtsal').val();
var Dept_Id = $('#ddllist').val();
$.ajax({
//var Data = "{ empname:" + name + "}";
url: 'jdatatable.aspx/update',//my .aspx page name
type: "POST",
data: '{ id: ' + id + ',empname: "' + name + '", sal: ' +sal + ', Dept_Id: ' + Dept_Id + ' }',
contentType: "application/json; charset=utf-8",
dataType: "json",
"success": function (data) {
alert("successfully done");
table.ajax.reload();
$('#txtempname').val('');
$('#txtsal').val('');
$('#ddllist').val('');
},
"error": function (data, xhr, status) {
alert(status);
}
});
jdatatable.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
}
}
//mymethod
[System.Web.Services.WebMethod]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json, XmlSerializeString = false)]
public void update(int id, string empname, int sal, int Dept_Id)
{
string s = ConfigurationManager.ConnectionStrings["dbconn"].ToString();
List<UserDetails> li = new List<UserDetails>();
SqlConnection con = new SqlConnection(s);
con.Open();
SqlCommand cmd = new SqlCommand("sp_update", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#id", id));
cmd.Parameters.Add(new SqlParameter("#Emp_Name", empname));
cmd.Parameters.Add(new SqlParameter("#Sal", sal));
cmd.Parameters.Add(new SqlParameter("#Dept_Id", Dept_Id));
cmd.ExecuteNonQuery();
con.Close();
}

Textbox Change Event not working

I have two Textboxes,I'm trying to fill the Second Textbox at change Event of Textbox1
Eg:
I have to fill the Customer Name when i type the Customer Code at TextBox1.
MY Script:
$(document).ready(function() {
userCodeChangeEvent();
});
function userCodeChangeEvent() {
$('#<%=txtCustomerCode.ClientID %>').change(function() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Customer_Bill.aspx/GetNameByCode",
data: "{'CusName':'" + document.getElementById('<%=txtCustomerCode.ClientID %>').value + "'}",
dataType: "json",
success: function(data) {
$('#<%=txtcustomerName.ClientID %>').value = data.d;
},
error: function(result) {
alert("No Match");
}
});
});
}
C#:
[WebMethod]
public static string GetNameByCode(string CusName)
{
// List<string> empResult = new List<string>();
string empResult = "";
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Constring"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select user_name From tbl_member_Registration where user_code=#SearchEmpName";
cmd.Connection = con;
con.Open();
cmd.Parameters.AddWithValue("#SearchEmpName", CusName);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
empResult=dr["user_name"].ToString();
}
con.Close();
return empResult;
}
}
}
but it doesn't working .How do i Solve this?
In client side 2 things you should notice :
1- $(...).val(data.d);
2- use "keyup" instead "change" because change will not be fired while the user is typing.
In Server side make sure that you enabled "ScriptService" by adding the [System.Web.Script.Services.ScriptService] attribute to the web service class (code behind the asmx) as the following:
[System.Web.Script.Services.ScriptService]
public class WS : System.Web.Services.WebService
{
[WebMethod]
public static string GetNameByCode(string CusName)
{
...
}
}
In your success function use val() instead of val= like this
success: function(data) {
$('#<%=txtcustomerName.ClientID %>').val(data.d);
}
,
And if necessary change this line also
data: "{'CusName':'" + $('#<%=txtCustomerCode.ClientID %>').val() + "'}",

Jquery AutoComplete with database

I cannot seem to figure out what is wrong with the code for the autocomplete search bar.
The only thing I can think of is that I referenced the wrong thing under URL
aspx Javascript
$(document).ready(function() {
SearchText();
});
function SearchText() {
$(".ui-autocomplete").autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Admin_home.aspx/GetAutoCompleteData",
data: "{'Car':'" + document.getElementById('query').value + "'}",
dataType: "json",
success: function(data) {
response(data.d);
},
Error: function(results) {
alert("Error");
}
});
}
});
}
</script>`
aspx html code
I cant seem to type or paste the html here. It is just a
asp:Textbox ID="query" class="ui.autocomplete"
c# code
[WebMethod]
public static List<string> GetAutoCompleteData(string Car)
{
List<string> result = new List<string>();
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["CarsConnectionString"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("select DISTINCT Car from T_Car where Car like '%'+ #SearchText +'%", con))
{
con.Open();
cmd.Parameters.AddWithValue("#SearchText", Car);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["Car"].ToString());
}
return result;
}
}
}
Would part of the html need to be wrapped in an AJAX update panel?
Also, I am having the search pull names from sql server 2005.
that is not how jQuery Autocomplete works,
jQuery autocomplete automatically sends the text entered in the text box to the location you specify in a querystring "term" you access it in webmethod or handler like this
string input = HttpContext.Current.Request.QueryString["term"];
something like this
[WebMethod]
public static List<string> GetAutoCompleteData(string Car)
{
string input = HttpContext.Current.Request.QueryString["term"];
List<string> result = new List<string>();
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["CarsConnectionString"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("select DISTINCT Car from T_Car where Car like '%'+ #SearchText +'%", con))
{
con.Open();
cmd.Parameters.AddWithValue("#SearchText", input);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["Car"].ToString());
}
return result;
}
}
}
this goes in your .aspx page
$(".ui-autocomplete").autocomplete({
source: "Admin_home.aspx/GetAutoCompleteData",
select: function (event, ui) { }
});
EDIT:
I've never actually done this in web method , I usually use a handler .ashx , but this should work just as good.
when you have all that changed , then run the site in debug mode, start to type in the textbox and fit f12 and watch the traffic that this is causing - if you type "abc" it should look like
Admin_home.aspx/GetAutoCompleteData?term=abc
then the response you might have to play with a little , by default .net is going to add "d : ...." to the response to client side , but you can watch it and adjust accordinly
Another Edit:
<asp:Textbox ID="query" class="ui.autocomplete">
is not what you put in the jquery
$(".ui-autocomplete").autocomplete({
it should be
<asp:Textbox ID="query" class="ui-autocomplete">
Yet, Another Edit:
This is missing a single quote
using (SqlCommand cmd = new SqlCommand("select DISTINCT Car from T_Car where Car like '%'+ #SearchText +'%", con))
replace with
using (SqlCommand cmd = new SqlCommand("select DISTINCT Car from T_Car where Car like '%'+ #SearchText +'%' ", con))
try this maybe it would help
<script type="text/javascript">
$(function() {
$(".ui-autocomplete").autocomplete({
source: function(request, response) {
$.ajax({
url: "Admin_home.aspx/GetAutoCompleteData",
data: "{ 'Car': '" + 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
}
}))
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2
});
});
</script>

Categories

Resources