Binding image in AutoCompleteExtender like facebook? - c#

i have an ajax AutoCompleteExtender. I am able to bind the text only with my AutoCompleteExtender not image. So How can i bind the image and text in an ajax AutoCompleteExtender? Any help is greatly appreciated.

Add below mentioned files in your header section
<script type="text/javascript">
$(document).ready(function () {
$("#searchtext").autocomplete
({
source:
function (request, response) {
$.ajax
({
url: "../BeanService.asmx/GetCompletionList",
data: "{prefixText:'" + request.term + "'}", // term is the property that contains the entered text
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response(data["d"]); // property d contains list of names sent from service
//$("#dynamiccontainer").append(data["d"]);
},
error: function (xhr, callStatus, errorThrown) {
// alert(callStatus);
}
});
},
// Attempt to remove click/select functionality - may be a better way to do this
select: function (event, ui) {
var mylink = ui.item.value;
var doc = document.createElement("html");
doc.innerHTML = mylink;
var links = doc.getElementsByTagName("a")
var urls = [];
for (var i = 0; i < links.length; i++) {
urls.push(links[i].getAttribute("href"));
}
window.location.href = urls[0];
return false;
}
});
});
</script>
Below is the Textbox on which autocomplete will be applied
<asp:TextBox ID="searchtext" runat="server"></asp:TextBox>
This is your bean class which will be filled by webservice and returned to jquery method through ajax call
public class SearchBean
{
public int Id
{
get;
set;
}
public string Title
{
get;
set;
}
public string reUrl
{
get;
set;
}
public string stype
{
get;
set;
}
public string photoAdd
{
get;
set;
}
}
This is your webservice which will be called by your jquery automplete ajax method
public string[] GetCompletionList(string prefixText)
{
BDBEntities db = new BDBEntities();
List<SearchBean> lstfinaldata = new List<SearchBean>();
List<MaCatMaster> lstcatlist = db.MaCatMasters.Where(z => z.CatName.Contains(prefixText) && z.Status == true).ToList();
foreach (MaCatMaster obj in lstcatlist)
{
SearchBean objbean = new SearchBean();
objbean.Id = obj.Id;
objbean.Title = obj.CatName;
objbean.stype = "Category";
objbean.reUrl = www.demo.com + "/Pages/Coupons/" + obj.Id;
lstfinaldata.Add(objbean);
}
string[] st = new string[lstfinaldata.Count];
int i = 0;
foreach (SearchBean obj in lstfinaldata)
{
StringBuilder sb = new StringBuilder();
sb.Append("<html><body>");
sb.AppendFormat("<a href='{0}' name='urllink'>", obj.reUrl);
sb.Append("<table width='420px'>");
sb.AppendFormat("<tr><td width='60px'><img src='{0}' style='border:1px solid #eeeeee' width='60px' height='40px'></td><td align='left' width='300px'>{1}</td><td align='left' width='60px' style='font-size:14px;'>{2}</td></tr>", obj.photoAdd, obj.Title, obj.stype);
sb.Append("</table>");
sb.Append("</a>");
sb.Append("</body></html>");
st[i] = sb.ToString();
i++;
}
return st;
}

In your search method you can use AutoCompleteExtender.CreateAutoCompleteItem() method to create pairs of the text to display and the image path:
public static List<string> Search(string prefixText, int count)
{
var items = new List<string>();
// ...
items.Add(AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(
text,
imagePath));
// ...
return items;
}
Then create the img tags on the client side with a javascript:
function Items_Populated(sender, e) {
var items = sender.get_completionList().childNodes;
for (var i = 0; i < items.length; i++) {
var div = document.createElement(“div”);
div.innerHTML = ”<img src=' + items[i]._value + ’ /><br />”;
items[i].appendChild(div);
}
Here are some examples:
AJAX AutoComplete with prefix image
Auto Complete with images

Related

Ajax callback issue

I got an project in dotnet and i'm trying to use GoogleCharts, but it's not working.
The project is on .net mvc
Here is my code:
Views->Sensor->Chart.cshtml
#{
ViewData["Title"] = "Chart";
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
<script type="text/javascript">
google.charts.load('current', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(LoadData);
function LoadData() {
$.ajax({
url: '#Url.Action("ChartJson","Sensor")',
dataType: "json",
type: "GET",
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
toastr.error(err.message);
},
success: function(data) {
CreateChart(data);
return false;
}
});
return false;
}
function CreateChart(data) {
var dataArray = [
['Tag', 'Average value']
];
$.each(data, function(i, item) {
dataArray.push([item.tag, item.value]);
});
var data = google.visualization.arrayToDataTable(dataArray);
var options = {
title: 'Sensor data per coutry and region',
chartArea: {
width: '50%'
},
colors: ['#b0120a', '#ffab91'],
hAxis: {
title: 'Arithmetic average',
minValue: 0
},
vAxis: {
title: 'Tag'
}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
return false;
}
</script>
This view is loaded on the url, but there is no graph on it.
I thied to debug the controller class, but the ChartJson() method is never called.
This is the two methods on the controller for the charts draw routine:
Controllers->SensorController.cs
public IActionResult Chart()
{
return View();
}
public JsonResult ChartJson()
{
var sensors = from s in _context.Sensor select s;
var sensorsList = sensors.ToList();
Console.WriteLine("Entrou");
List<ChartData> listChart = new List<ChartData>();
foreach (Sensor s in sensorsList)
{
int value;
bool isNumeric = int.TryParse(s.value, out value);
if (!isNumeric)
continue;
string tag = s.country + "." + s.region;
for (int i = 0; i < listChart.Count; i++)
{
if (listChart[i].tag.Equals(tag))
{
listChart[i].AddValue(value);
break;
}
if (i == listChart.Count - 1)
{
listChart.Add(new ChartData(tag));
break;
}
}
}
return Json(listChart);
}
Can anyone help me? Thanks.

Button Click is not working after WebMethod function

On my web page I used jquery and ajax to call a C# function to fill Dropdown list with respect to another
Dropdown Branch is filled as per the selection of zone and Employee with the selection of branch.It works perfect But the button Click is not working after this.Someone please tell me why this button click is not working??
[Button click works when no drop down selection is made]
my Code look Like this:
Jquery
<script src="jquery-1.11.1.min.js"></script>
<script type="text/javascript">
$(function () {
$('#<%= ddZone.ClientID %>').change(function () {
$.ajax({
type: "POST",
url: "Reports.aspx/BranchFill",
data: "{'Zone':'" + $("[id*=ddZone] option:selected").text() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
function OnSuccess(response) {
var ddlBranch = $("[id*=ddBranch]");
ddlBranch.empty().append('<option selected="selected" value="0">--Select--</option>');
$.each(response.d, function () {
ddlBranch.append($("<option></option>").val(this['Value']).html(this['Text']));
});
if (response.d == "false") {
alert("Not found");
}
}
});
$('#<%= ddBranch.ClientID %>').change(function () {
$.ajax({
type: "POST",
url: "Reports.aspx/EmployeeFill",
data: "{'Branch':'" + $(this).val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
function OnSuccess(response) {
var ddlEmployee = $("[id*=ddEmployee]");
ddlEmployee.empty().append('<option selected="selected" value="0">--Select--</option>');
$.each(response.d, function () {
ddlEmployee.append($("<option></option>").val(this['Value']).html(this['Text']));
});
if (response.d == "false") {
alert("Not found");
}
}
});
});
</script>
C#
[System.Web.Services.WebMethod(EnableSession = true)]
public static Object BranchFill(string Zone)
{
string result = string.Empty;
var obj = new Reports();
List<ListItem> Branch = new List<ListItem>();
DataTable dt = obj.CS.StaticZoneBranch(Zone, "", "SelectBranch");
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
Branch.Add(new ListItem
{
Text = dt.Rows[i]["Name"].ToString(),
Value = dt.Rows[i]["Code"].ToString()
});
}
return Branch;
}
else
{
return "false";
}
}
[System.Web.Services.WebMethod(EnableSession = true)]
public static Object EmployeeFill(string Branch)
{
string result = string.Empty;
var obj = new Reports();
List<ListItem> Employee = new List<ListItem>();
DataTable dt = obj.CS.StaticZoneBranch("", Branch, "SelectEmployee");
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
Employee.Add(new ListItem
{
Text = dt.Rows[i]["Name"].ToString(),
Value = dt.Rows[i]["Employee Id"].ToString()
});
}
return Employee;
}
else
{
return "false";
}
}
And the button Click(which is not working)
protected void Button1_Click(object sender, EventArgs e)
{
ReportClass RC = new ReportClass();
if (ddZone.SelectedValue !="0")
{
RC.Zone = ddZone.SelectedValue;
RC.Branch = ddBranch.SelectedValue;
RC.EmployeeId = ddEmployee.SelectedValue;
Report = RC.GetReport();
}
}
Why this click function is not Working, please help me to know..

First Row activate Works only in activate all button jQuery c#

This is my c# code for Activate all button:
[WebMethod]
public static void ActivateSelected(String Id)
{
clsCategoryBL objproject = new clsCategoryBL();
string[] arr = Id.Split(',');
string strid = arr[2];
foreach (var id in arr)
{
if (!string.IsNullOrEmpty(id))
{
objproject.CategoryStatus(Convert.ToInt32(strid), true);
}
}
BindDatatable();
}
This is my jquery table bind code:
function ActivateSelected() {
var ids = '';
var cells = Array.prototype.slice.call(document.getElementById("example1").getElementsByTagName('td'));
debugger;
for (var i in cells) {
var inputArray = cells[i].getElementsByTagName('input');
for (var i = 0; i < inputArray.length; i++) {
if (inputArray[i].type == 'checkbox' && inputArray[i].checked == true) {
debugger;
ids += inputArray[i].id + ',';
}
}
}
debugger;
var urldata = "Category.aspx/ActivateSelected";
$.ajax(
{
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: "true",
cache: "false",
url: urldata,
data: "{Id:'" + ids + "'}",
success: function (dt) {
debugger;
location.reload();
$("#example1").DataTable();
//$("#example1").bind;
debugger;
},
error: function (result) {
alert("Error");
//console.log();
//alert(result);
}
});
}
The problem is that when select all the checkbox and click on Activate all button only First row status is activate instead of All row status,So kindly help me out.
This is my activate all button:
<i class="fa fa-check-square-o" name="activatebtn" onclick='ActivateSelected();' style='font-size:22px;margin-left: 32px;color:green'>Activate Selected</i>
This is the code for select all the checkbox:
function Selectallcheckbox() {
var cells = Array.prototype.slice.call(document.getElementById("example1").getElementsByTagName('td'));
var check = document.getElementById('chkall');
if (check.checked) {
for (var i in cells) {
var inputArray = cells[i].getElementsByClassName('chk');
for (var i = 0; i < inputArray.length; i++) {
inputArray[i].checked = true;
}
}
}
else {
for (var i in cells) {
var inputArray = cells[i].getElementsByClassName('chk');
for (var i = 0; i < inputArray.length; i++) {
inputArray[i].checked = false;
}
}
}
}
I think the problem is here(c#):
string strid = arr[2];
In strid only one id is comes..and only one id is binding in
objproject.CategoryStatus(Convert.ToInt32(strid), true);
If i am using Id instead of strid on above line it provides me error due to last comma..input string was not in correct format..
Edit this line to objproject.CategoryStatus(Convert.ToInt32(id), true); I have changed strid to id the foreach loop variable.

how to post json array list to web service method?

i write two functions in jquery client side and c# asp.net server side , i try post json list object to web method but i see error..
jquery code :
function UpdateCart(tableid) {
var page = "Account/Cart.aspx";
var method = "Update_Cart";
var url = "http://" + host + "/" + page + "/" + method;
$(".popup").show();
var cartlist = new Array();
for (var i = 68; i < 71; i++) {
var cart = new Object();
cart.ID = i;
cart.Quantity = 6;
cartlist.push(cart);
}
var jsonArray = JSON.parse(JSON.stringify(cartlist))
$.ajax({
type: "POST",
url: url,
data: jsonArray,
contentType: "application/json; charset=utf-8",
datatype: "json",
async: "true",
success: function (response) {
// success message or do
$(".errMsg ul").remove();
var myObject = eval('(' + response.d + ')');
if (myObject == 1) {
window.location.href = "http://" + host + "/Account/cart";
} else {
$(".errMsg").text("نام کاربری یا رمز اشتباه است");
$(".errMsg").removeClass("alert");
$(".errMsg").addClass("alert alert-danger");
}
},
error: function (response) {
alert(response.status + ' ' + response.statusText);
}
});
}
c# web method :
[WebMethod]
public static string Update_Cart(string[] Carts)
{
if (Carts != null)
{
foreach (var item in Carts)
{
com_Shop_Carts cart = new com_Shop_Carts()
{
Quantity = item.Quantity,
AddDate = DateTime.Now
};
com.shop.ProductManager.Update_Cart(item.ID, cart).ToString();
}
}
return "1";
}
after run i see error 500 and i can't resolve it please give me solution for resolve it.
Apart from this : var jsonArray = JSON.parse(JSON.stringify(cartlist))
Try this : var json={"Carts":cartlist}; then, var jsonArray=JSON.stringify(json);
and remove datatype:json from the ajax call.
Hope this helps.

Can't set selected value in select2 plugin in Bootstrap

I use a select2 plugin my website. I can't set selected value in select2. Please see my code below.
Html
<input id="drpEditProvider" class="form-control" type="text" value="" tabindex="8" name="ProviderId" data-required="true" />
Script
var attendeeUrl = '#Url.Action("GetProvider", "Admin")';
var pageSize = 100;
$('#drpEditProvider').select2(
{
placeholder: 'Please Select Provider',
//Does the user have to enter any data before sending the ajax request
minimumInputLength: 0,
allowClear: true,
//tags:["red", "green", "blue"],
ajax: {
////How long the user has to pause their typing before sending the next request
//quietMillis: 150,
//The url of the json service
url: attendeeUrl,
dataType: 'jsonp',
//Our search term and what page we are on
data: function (term, page) {
return {
pageSize: pageSize,
pageNum: page,
searchTerm: term
};
},
results: function (data, page) {
//Used to determine whether or not there are more results available,
//and if requests for more data should be sent in the infinite scrolling
var more = (page * pageSize) < data.Total;
return { results: data.Results, more: more };
}
},
initSelection: function (element, callback) {
var data = [];
$(element.val().split(",")).each(function () {
data.push({ id: this, text: this });
});
callback(data);
},
});
Controller and model
public class Select2PagedResult
{
public int Total { get; set; }
public List<Select2Result> Results { get; set; }
}
public class Select2Result
{
public string id { get; set; }
public string text { get; set; }
}
public JsonResult GetProvider(string searchTerm, int pageSize, int pageNum)
{
int Count = 0;
List<Provider> provideres = ProviderHelper.GetAllProvider(searchTerm, out Count);
//Translate the attendees into a format the select2 dropdown expects
Select2PagedResult pagedProvider = new Select2PagedResult();
pagedProvider.Results = new List<Select2Result>();
//Loop through our attendees and translate it into a text value and an id for the select list
foreach (Provider a in provideres)
{
pagedProvider.Results.Add(new Select2Result { id = a.Id.ToString(), text = a.Name });
}
//Set the total count of the results from the query.
pagedProvider.Total = Count;
//Return the data as a jsonp result
return new JsonpResult
{
Data = pagedProvider,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
Finally I found the answer. You can set selected value in select2 plugin like below.
Select 2 Single selection
$("#drpselector").select2("data", { id: "1", text:"Test 1" });
Select 2 Multiple selection
var arrdata = "1:Test 1,2:Test 2"
var thdprdata = [];
$(arrdata.split(",")).each(function () {
thdprdata.push({ id: this.split(':')[0], text: this.split(':')[1] });});
$("#drpselector").select2("data", thdprdata);
I use this code in my application. It works fine for me.

Categories