Related
I am using visual studio 2019 and developing a MVC application. I want to render a chart between in-time (on Y-Axis) and attendance date (on X-Axis) for employee attendance date wise. I am getting all those data of the employee as an object list. Please refer screenshots. Attendance Date Object List
Punch In-Time Object List
I am using Chart.js (V 3.7.1) in MVC application. I have googled a lot but can't find the solution. I am new to this platform, please help me out to find out the solution to do that? Thanks in advance.
Here is my code of Action Method:
[HttpGet]
public ActionResult BarChart()
{
try
{
List<object> iData = new List<object>();
DataTable dt = new DataTable();
using (OracleConnection con = new OracleConnection(AppSetting.OraConnectionString()))
{
string str = #"SELECT to_char(cast(EAE_DATE as date),'dd-MON-yy') AS EAE_DATE ,to_char(cast(IN_TIME as date),'hh24:mi:ss') AS IN_TIME,to_char(cast(OUT_TIME as date),'hh24:mi:ss') AS OUT_TIME FROM EMPLOYEE_DAILY_ATTENDANCE_EXL WHERE EAE_EM_ID = 904 AND EAE_YEAR=2022 AND EAE_MONTH=11 ORDER BY EAE_DATE";
OracleDataAdapter da = new OracleDataAdapter(str, con);
da.Fill(dt);
foreach (DataColumn dc in dt.Columns)
{
List<object> x = new List<object>();
x = (from DataRow drr in dt.Rows select drr[dc.ColumnName]).ToList();
iData.Add(x);
}
ViewBag.Date_List = iData[0];
ViewBag.InTime_List = iData[1];
ViewBag.OutTime_List = iData[2];
}
return View();
}
catch (Exception)
{
throw;
}
}
And View code is:
#{
ViewBag.Title = "BarChart";
}
<div style="text-align: center">
<canvas id="barcanvas"></canvas>
</div>
<meta name="viewport" content="width=device-width" />
<title>Attendance Punctuality</title>
#* I have installed Chart.js from ManageNugetPackages so not using the cdn *#
<script>
var DayDate =#Html.Raw(Json.Encode(ViewBag.Date_List));
var InTime =#Html.Raw(Json.Encode(ViewBag.InTime_List));
var OutTime =#Html.Raw(Json.Encode(ViewBag.OutTime_List));
var ChartData =
{ labels: DayDate,
datasets: [{
label: 'In Time',
backgroundColor: "#aad2ed",
borderWidth: 2,
data: InTime,
borderColor: '#0062ff',
fill: false,
},
{
label: 'Out Time',
backgroundColor: "#f7bd83",
borderWidth: 2,
data: OutTime,
borderColor: '#F78511',
fill: false,
}]
};
window.onload = function () {
var ctx1 = document.getElementById("barcanvas").getContext("2d");
window.myBar = new Chart(ctx1,
{ type: 'line', //line,pie,bar,doughnut
data: ChartData,
showDatapoints: true,
legend: { position: 'bottom' },
options:
{
title: { display: true, text: "Attendance Trial Graph"},
responsive: true,
maintainAspectRatio: true
}
});
}
</script>
I am trying to auto complete a text box with Names from a database. When I go to type in the text box when it is running nothing happens.
I have been following this tutorial but am unable to get it working.
http://www.dotnetodyssey.com/2015/01/14/autocomplete-textbox-using-jquery-asp-net-querying-database-complete-example/
Source code below.
The Aspx page:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="jquery-1.11.2.min.js"></script>
<script type="text/javascript" src="jquery-ui.min.js"></script>
<link href="jquery-ui.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript">
$(document).ready(function () {
$("#txtNames").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "WebForm1.aspx/GetNames",
data: "{'namePrefix':'" + $("#txtNames").val() + "'}",
dataType: "json",
minLength: 2,
success: function (data) {
response(data.d)
},
error: function (response) {
alert("Error" + res.responseText);
}
});
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<label for="txtNames">Names:</label>
<asp:TextBox ID="txtNames" runat="server"></asp:TextBox>
</div>
</form>
</body>
</html>
The Code Behind:
[WebMethod]
public static string[] GetNames(string namePrefix)
{
List<string> Name = new List<string>();
DataTable dtNames = new DataTable();
string sqlQuery = "select distinct Name from Houses where Name like '" + namePrefix + "%'";
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
try
{
SqlConnection conn = new SqlConnection(connectionString);
SqlDataAdapter da = new SqlDataAdapter(sqlQuery, conn);
da.Fill(dtNames);
foreach (DataRow row in dtNames.Rows)
{
string name = Convert.ToString(row["Name"]);
Name.Add(name);
}
}
catch (Exception ex)
{
throw ex;
}
return Name.ToArray<string>();
}
Here is an example of autocomplete textbox:
private void LoadServices()
{
txtServiceName.AutoCompleteMode = AutoCompleteMode.Suggest;
txtServiceName.AutoCompleteSource = AutoCompleteSource.CustomSource;
txtServiceName.AutoCompleteCustomSource = colValues;
}
And:
AutoCompleteStringCollection colValues = new AutoCompleteStringCollection();
private void GetAllServices()
{
// get list of Windows services
ServiceController[] services = ServiceController.GetServices();
List<string> ac = new List<string>();
// try to find service name
foreach (ServiceController service in services)
{
ac.Add(service.ServiceName.ToString());
}
colValues.AddRange(ac.ToArray());
}
I am using a map control from telerik, with shome markers:
#(Html.Kendo().Map()
.Name("map")
.Layers(layers =>
{
layers.Add()
.Type(MapLayerType.Tile)
.UrlTemplate("http://tile.openstreetmap.org/#= zoom #/#= x #/#= y #.png")
.Subdomains("a", "b", "c")
.Attribution("© <a href='http://osm.org/copyright'>OpenStreetMap contributors</a>." +
"Tiles courtesy of <a href='http://www.opencyclemap.org/'>Andy Allan</a>");
layers.Add()
.Type(MapLayerType.Marker)
.DataSource(dataSource => dataSource.GeoJson()
.Read(read => read.Action("GetMarkers", "MyController"))
)
.Tooltip(t => t.ContentHandler("GetTooltipContent"))
.LocationField("LatLng")
.TitleField("Title");
}).Events(e => e.MarkerClick("MarkerClicked")))
I need that all markers fit in the initial map view, with the correct zoom and center location.
I have used the gmaps javascript plugin for google maps and I know there are functions fitZoom()/fitBounds() to achieve this
Is there any way to achieve this with Kendo controls?
Using jQuery you can set bound for map.
function createMap() {
var markers = [
{"latlng":[34.2675,38.7409], "name": "One"},
{"latlng": [30.2707,-97.7490],"name": "Two"},
{"latlng": [30.2705,-90.4444],"name": "Three"},
{"latlng": [31.8520,33.8911], "name": "Four"}];
$("#map").kendoMap({
layers: [{
type: "tile",
urlTemplate: "http://tile.openstreetmap.org/#= zoom #/#= x #/#= y #.png",
subdomains: ["a", "b", "c"],
attribution: "© <a href='http://osm.org/copyright'>OpenStreetMap contributors</a>." +
"Tiles courtesy of <a href='http://www.opencyclemap.org/'>Andy Allan</a>"
}, {
type: "marker",
dataSource: {
data: markers
},
locationField: "latlng",
titleField: "name"
}]
});
var map = $("#map").getKendoMap();
var layer = map.layers[1];
var markers = layer.items;
var extent;
for (var i = 0; i < markers.length; i++) {
var loc = markers[i].location();
if (!extent) {
extent = new kendo.dataviz.map.Extent(loc, loc);
} else {
extent.include(loc);
}
}
map.extent(extent);
}
$(document).ready(createMap);
<!DOCTYPE html>
<html>
<head>
<base href="http://demos.telerik.com/kendo-ui/map/index">
<style>html { font-size: 12px; font-family: Arial, Helvetica, sans-serif; }</style>
<title></title>
<link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.318/styles/kendo.common-material.min.css" />
<link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.318/styles/kendo.material.min.css" />
<link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.318/styles/kendo.dataviz.min.css" />
<link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.318/styles/kendo.dataviz.material.min.css" />
<script src="http://cdn.kendostatic.com/2015.1.318/js/jquery.min.js"></script>
<script src="http://cdn.kendostatic.com/2015.1.318/js/kendo.all.min.js"></script>
</head>
<body>
<div id="example">
<div class="demo-section k-header" style="padding: 1em;">
<div id="map"></div>
</div>
</div>
</body>
</html>
I did that with an ajax call in an asp.net mvc5 application
the controller
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
return View();
}
public ActionResult GetMarkers( )
{
var listMarkers = new List<Markers>() { new Markers() { Latitude=34.2675, Longitude= 38.7409, Name="Pos1"},
new Markers() { Latitude=30.2707, Longitude=-97.7490, Name="Pos2"},
new Markers() { Latitude=30.2705, Longitude=-90.4444, Name="Pos3"},
new Markers() { Latitude=31.8520, Longitude=33.8911, Name="Pos4"},
new Markers() { Latitude=33.8520, Longitude=32.8911, Name="Pos5"},
new Markers() { Latitude=60.2707, Longitude=-97.7490, Name="Pos6"},
new Markers() { Latitude=20.2705, Longitude=-90.4444, Name="Pos7"},
new Markers() { Latitude=50.8520, Longitude=33.8911, Name="Pos8"},
new Markers() { Latitude=40.8520, Longitude=32.8911, Name="Pos9"}};
var json = JsonConvert.SerializeObject(listMarkers);
return Json(json, JsonRequestBehavior.AllowGet);
}
}
The Model:
public class Markers
{
public string Name { get; set; }
public double Latitude { get; set; }
public double Longitude { get; set; }
public double[] LatLong { get { return new double[] { Latitude , Longitude}; } }
}
and the view
<ul id="panelbar">
<li class="k-state-active">
<span class="k-link k-state-selected">Getting Started</span>
<div id="map" style="width: 960px; height: 600px"></div>
</li>
<li>
</li>
</ul>
<script>
$(function () {
var markers;
$.ajax({
url: "../Home/GetMarkers",
dataType: 'json',
async: false,
success: function (data) {
markers = data;
}
});
$("#panelbar").kendoPanelBar();
$("#map").kendoMap({
layers: [{
type: "tile",
urlTemplate: "http://a.tile.openstreetmap.org/#= zoom #/#= x #/#= y #.png",
attribution: "© <a href='http://osm.org/copyright'>OpenStreetMap contributors</a>."
}, {
type: "marker",
dataSource: {
data: JSON.parse(markers)
},
locationField: "LatLong",
titleField: "Name"
}]
});
});
</script>
Im Currently Stack on how to display all the data of my database im new in using JQGRID and i dont know why is my data dont display when i deployed it on web using localhost
getdata.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Web.Services;
using System.Web.Script.Services;
using MySql.Data.MySqlClient;
public partial class getdata : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public struct s_GridResult
{
public int page;
public int total;
public int record;
public s_RowData[] rows;
}
public struct s_RowData
{
public int id;
public string[] cell;
}
[WebMethod]
public static s_GridResult GetDataTable(string _search, string nd, int rows, int page,
string sidx, string sord)
{
int startindex = (page - 1);
int endindex = page;
string sql = "SELECT ItemCode,PartNumber FROM tblitemcodefromqne";
DataTable dt = new DataTable();
MySqlConnection conn = new
MySqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString1"].ConnectionString);
MySqlDataAdapter adapter = new MySqlDataAdapter(sql, conn);
adapter.Fill(dt);
s_GridResult result = new s_GridResult();
List<s_RowData> rowsadded = new List<s_RowData>();
int idx = 1;
foreach (DataRow row in dt.Rows)
{
s_RowData newrow = new s_RowData();
newrow.id = idx++;
newrow.cell = new string[2]; //total number of columns
newrow.cell[0] = row[0].ToString();
newrow.cell[1] = row[1].ToString();
rowsadded.Add(newrow);
}
result.rows = rowsadded.ToArray();
result.page = page;
result.total = dt.Rows.Count;
result.record = rowsadded.Count;
return result;
}
}
getdata.aspx
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1
/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<link rel="Stylesheet" type="text/css" media="screen" href="JQGridReq/jquery-
ui-1.9.2.custom.css" />
<link rel="Stylesheet" type="text/css" media="screen" href="JQGridReq/ui.jqgrid.css" />
<link rel="Stylesheet" type="text/css" media="screen" href="Themes/style.css" />
<script type="text/javascript" src="JQGridReq/jquery-1.9.0.min.js"></script>
<script type="text/javascript" src="JQGridReq/jquery.json-2.2.min.js"></script>
<script type="text/javascript" src="JQGridReq/jquery-ui-1.9.4.custom.min.js"></script>
<script type="text/javascript" src="JQGridReq/grid.locale-en.js"></script>
<script type="text/javascript" src="JQGridReq/jquery.jqGrid.js"></script>
<script type="text/javascript" >
$(document).ready(function () {
$.extend($.jgrid.defaults,
{ datatype: 'json' },
{ ajaxGridOptions: { contentType: "application/json",
success: function (data, textStatus) {
if (textStatus == "success") {
var thegrid = $("#Grid1")[0];
thegrid.addJSONData(data.d);
thegrid.grid.hDiv.loading = false;
switch (thegrid.p.loadui) {
case "disable":
break;
case "enable":
$("#load_" + thegrid.p.id).hide();
break;
case "block":
$("#lui_" + thegrid.p.id).hide();
$("#load_" + thegrid.p.id).hide();
break;
}
}
}
}
});
jQuery("#Grid1").jqGrid({
url: 'getdata.aspx/GetDataTable',
datatype: 'json',
mtype: 'POST',
colNames: ['Item Code', 'Part Number'],
colModel: [{ name: 'ItemCode', index: 'ItemCode', width: 200 },
{ name: 'PartNumber', index: 'PartNumber', width: 300}],
pager: '#pager', sortname: 'ItemCode',
viewrecoreds: true,
imgpath: 'JQGridReq/images',
serializeGridData: function (data) {
return $.toJSON(data);
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<table id="Grid1" class="scroll" align="center" width="100%"></table>
<div id="pager" class="scroll" style="text-align:center;">
</div>
</form>
</body>
</html>
The field names of the database table should match with the name in the colmodel which is in the javascript.
The java script
<script language="javascript" type="text/javascript">
$(function() {
var grid = jQuery("#myGrid");
grid.jqGrid({
url: "http://localhost:50530/jqGridHandler.ashx",
mtype:'GET',
datatype: "json",
height: 200,
hidegrid: false,//hides the arrow button at the top right corner for collapsing the jqGrid
rowNum: 10,
rowList: [10, 20, 30],
viewrecords: true,
caption: "Employees",
pager: "#pager",
colNames: ['FirstName', 'SecondName', 'DOB', 'EmailID','UserName'],
colModel: [
{ name: 'FirstName', index: 'FirstName', width: 100, align: "center" },
{ name: 'LastName', index: 'LastName', width: 100, align: "left" },
{ name: 'DOB', index: 'DOB', width: 100, align: "center", formatter: 'date', formatoptions: { newformat: 'm-d-Y' }, datefmt: 'm-d-Y' },
{ name: 'Email', index: 'EmailID', width: 120, align: "right"},
{ name: 'Username', index: 'Username', width: 100 }
]
});
});
</script>
the web component
<table id="myGrid"> </table>
the code behind (jqGridHandler.ashx)
public class jqGridHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
MyFirstService.Service1Client client = new MyFirstService.Service1Client();
context.Response.Write(client.GetJsonUsers());
}
private DataSet GetUsersFromDB()
{
AccessDataBase reader = new AccessDataBase();
string selectquery = "SELECT * FROM Registration";
return reader.readDB(selectquery);
}
public string GetJsonUsers()
{
return GetJson(GetUsersFromDB());
}
private string GetJson(DataSet dt)
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows =
new List<Dictionary<string, object>>();
Dictionary<string, object> row = null;
foreach (DataTable dtt in dt.Tables)
foreach (DataRow dr in dtt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dtt.Columns)
{
row.Add(col.ColumnName.Trim(), dr[col]);
}
rows.Add(row);
}
return serializer.Serialize(rows);
}
public bool IsReusable
{
get
{
return false;
}
}
}
AccessDB.cs
public SqlConnection Connection { get; set; }
public AccessDataBase()
{
Connection = new SqlConnection("Data Source=.;Initial Catalog=NewDB;Integrated Security=True");
}
public DataSet readDB(string selectquery)
{
SqlCommand cmd = new SqlCommand(selectquery);
using (Connection)
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = Connection;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds);
return ds;
}
}
}
}
and add
using System.Web.Script.Serialization;
and don forget to add the js and css files in the master page.
<link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
<link href="Scripts/JQGrid/jquery-ui-1.9.2.custom.css" rel="stylesheet" type="text/css" />
<link href="Scripts/JQGrid/ui.jqgrid.css" rel="stylesheet" type="text/css" />
<script src="Scripts/JQGrid/jquery-1.9.0.min.js" type="text/javascript"></script>
<script src="Scripts/JQGrid/jquery.jqGrid.js" type="text/javascript"></script>
<script src="Scripts/JQGrid/grid.locale-en.js" type="text/javascript"></script>
<script src="Scripts/JQGrid/jquery.jqGrid.min.js" type="text/javascript"></script>
I found out the answer by my self here's what i did to implement JQGrid on ASP.net and MySQL database.
ItemCode.ashx
public struct JQGridResults
{
public int page;
public int total;
public int records;
public JQGridRow[] rows;
}
public struct JQGridRow
{
public string ItemCode;
public string PartNumber;
public string ItemDescriptionShort;
public string ItemDescriptionLong;
public string ProductCode;
public string GroupCode;
public string BusinessUnit;
public string[] cell;
}
[Serializable]
public class User
{
public string ItemCode { get; set; }
public string PartNumber { get; set; }
public string ItemDescriptionShort { get; set; }
public string ItemDescriptionLong { get; set; }
public string ProductCode { get; set; }
public string GroupCode { get; set; }
public string BusinessUnit { get; set; }
}
public class ItemCode : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
HttpRequest request = context.Request;
HttpResponse response = context.Response;
string _search = request["_search"];
string numberOfRows = request["rows"];
string pageIndex = request["page"];
string sortColumnName = request["sidx"];
string sortOrderBy = request["sord"];
int totalRecords;
Collection <User> users = GetUsers(numberOfRows, pageIndex, sortColumnName,sortOrderBy, out totalRecords);
string output = BuildJQGridResults(users, Convert.ToInt32(numberOfRows),Convert.ToInt32(pageIndex), Convert.ToInt32(totalRecords));
response.Write(output);
}
private string BuildJQGridResults(Collection <User> users, int numberOfRows, int pageIndex, int totalRecords)
{
JQGridResults result = new JQGridResults();
List<JQGridRow> rows = new List<JQGridRow>();
foreach (User user in users)
{
JQGridRow row = new JQGridRow();
row.ItemCode = user.ItemCode;
row.PartNumber = user.PartNumber;
row.ItemDescriptionShort = user.ItemDescriptionShort;
row.ItemDescriptionLong = user.ItemDescriptionLong;
row.ProductCode = user.ProductCode;
row.GroupCode = user.GroupCode;
row.BusinessUnit = user.BusinessUnit;
rows.Add(row);
}
result.rows = rows.ToArray();
result.page = pageIndex;
result.total = (totalRecords + numberOfRows - 1) / 8;
result.records = totalRecords;
JavaScriptSerializer serializer = new JavaScriptSerializer() { MaxJsonLength = Int32.MaxValue, RecursionLimit = 100 };
//return new JavaScriptSerializer().Serialize(result);
return serializer.Serialize(result);
}
private Collection<User> GetUsers(string numberOfRows, string pageIndex, string sortColumnName, string sortOrderBy, out int totalRecords)
{
Collection<User> users = new Collection<User>();
MySqlConnection conn = Functions.GetConnection();
string sql;
sql = "SELECT * FROM swans.tblsomain,tblligerstatus;";
MySqlCommand cmd = new MySqlCommand(sql, conn);
MySqlDataReader data1 = cmd.ExecuteReader();
string connectionString = "server=127.0.0.1;database=swans;uid=root;password=''";
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
using (MySqlCommand command = new MySqlCommand())
{
command.Connection = connection;
command.CommandText = "select ItemCode,PartNumber,ItemDescriptionShort,ItemDescriptionLong,ProductCode,GroupCode,BusinessUnit from tblitemcodefromqne;";
command.CommandType = CommandType.Text;
MySqlParameter paramPageIndex = new MySqlParameter("#PageIndex",MySqlDbType.Int32);
paramPageIndex.Value = Convert.ToInt32(pageIndex);
command.Parameters.Add(paramPageIndex);
MySqlParameter paramColumnName = new MySqlParameter("#SortColumnName", MySqlDbType.VarChar, 50);
paramColumnName.Value = sortColumnName;
command.Parameters.Add(paramColumnName);
MySqlParameter paramSortorderBy = new MySqlParameter("#SortOrderBy", MySqlDbType.VarChar, 4);
paramSortorderBy.Value = sortOrderBy;
command.Parameters.Add(paramSortorderBy);
MySqlParameter paramNumberOfRows = new MySqlParameter("#NumberOfRows", MySqlDbType.Int32);
paramNumberOfRows.Value = Convert.ToInt32(numberOfRows);
command.Parameters.Add(paramNumberOfRows);
MySqlParameter paramTotalRecords = new MySqlParameter("#TotalRecords",MySqlDbType.Int32);
totalRecords = 0;
paramTotalRecords.Value = totalRecords;
paramTotalRecords.Direction = ParameterDirection.Output;
command.Parameters.Add(paramTotalRecords);
connection.Open();
using (MySqlDataReader dataReader = command.ExecuteReader())
{
User user;
while (dataReader.Read())
{
user = new User();
user.ItemCode = Convert.ToString(dataReader["ItemCode"]);
user.PartNumber = Convert.ToString(dataReader["PartNumber"]);
user.ItemDescriptionShort = Convert.ToString(dataReader["ItemDescriptionShort"]);
user.ItemDescriptionLong =Convert.ToString(dataReader["ItemDescriptionLong"]);
user.ProductCode = Convert.ToString(dataReader["ProductCode"]);
user.GroupCode = Convert.ToString(dataReader["GroupCode"]);
user.BusinessUnit = Convert.ToString(dataReader["BusinessUnit"]);
users.Add(user);
}
}
totalRecords = users.Count;
}
return users;
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
ItemCode.aspx
<script type="text/javascript" >
$(function () {
$("#UsersGrid").jqGrid({
type: 'POST',
url: 'ItemCode.ashx',
datatype: "json",
width: 1245,
height: 450,
serializeGridData: function (postData) {
return JSON.stringify(postData);
},
jsonReader: {
repeatitems: false,
root: "rows",
page: "page",
total: "total",
records: "records"
},
colNames: ['Item Code', 'Part Number', 'Short Description', 'Long Description', 'Product Code', 'Group Code', 'Business Unit'],
colModel: [
{ name: 'ItemCode', index: 'ItemCode', width: 60, editable:true, sorttype: 'string' },
{ name: 'PartNumber', index:'PartNumber', width: 50 },
{ name: 'ItemDescriptionShort',index:'ItemDescriptionShort', width: 260 },
{ name: 'ItemDescriptionLong',index:'ItemDescriptionLong', width: 260 },
{ name: 'ProductCode',index:'ProductCode', width: 50 },
{ name: 'GroupCode',index:'GroupCode', width: 50 },
{ name: 'BusinessUnit',index:'BusinessUnit', width: 50 },
],
cmTemplate: { title: false },
rowNum: 20,
mtype: 'GET',
loadonce: true,
rowList: [10, 20, 30],
pager: '#UsersGridPager',
sortname: 'ItemCode',
multiSort: true,
gridview: true,
viewrecords: true,
sortorder: 'asc',
caption: "Item Code Summary"
});
jQuery("#UsersGrid").jqGrid('navGrid', '#UsersGridPager',
{ del: false, add: false, edit: false, search: false });
jQuery("#UsersGrid").jqGrid('filterToolbar', { stringResult: true, searchOnEnter: false });
});
</script>
</head>
<body>
<form id="UsersForm" runat="server">
<table id="UsersGrid" ></table>
<div id="UsersGridPager"></div>
</form>
</body>
my database table TAGS(TagId,TagName) my web method code is as follows
public List<Tag> FetchTagList(string tag)
{
OleDbConnection cn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"|DataDirectory|\\ImageDB2.mdb\";Persist Security Info=True");
DataSet ds = new DataSet();
DataTable dt = new DataTable();
string query = "select * from TAGS Where TagName like '#myParameter'";
OleDbCommand cmd = new OleDbCommand(query,cn);
cmd.Parameters.AddWithValue("#myParameter", "%" + tag + "%");
try
{
cn.Open();
cmd.ExecuteNonQuery();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(ds);
}
catch(OleDbException excp)
{
}
finally
{
cn.Close();
}
dt = ds.Tables[0];
List<Tag> Items = new List<Tag>();
Tag obj;
foreach (DataRow row in dt.Rows)
{
obj = new Tag();
//String From DataBase(dbValues)
obj.TagName = row["TagName"].ToString();
obj.ID = Convert.ToInt32(row["TagId"].ToString());
Items.Add(obj);
}
return Items;
}
}
i used class
public class Tag
{
public int ID { get; set; }
public string TagName { get; set; }
}
my javascript code is
<link href="css/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="jsautocom/jquery.min.js" type="text/javascript"></script>
<script src="jsautocom/jquery-ui.min.js" type="text/javascript"></script><script type="text/javascript">
$(function () {
$(".tb").autocomplete({
source: function (request, response) {
$.ajax({
url: "WebService.asmx/FetchTagList",
data: "{ 'tag': '" + 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.TagName
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 1
});
});
</script>
my aspx page is as like
<div class="demo">
<div class="ui-widget">
<label for="tbAuto">Search Tag: </label>
<asp:TextBox ID="TextBox1" class="tb" runat="server" ontextchanged="TextBox1_TextChanged"></asp:TextBox>
<asp:Button ID="btnSearch" runat="server" CssClass="btnSearch"
onclick="btnSearch_Click" Text="Search" />
</div>
</div>
but i get nothing.how to solve it.any one helps me is greatly appreciated.thanks in advance
just change the data and response in the ajax as given below
data: "{'PhoneContactName':'" + document.getElementById("<%= ContactName.ClientID %>").value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
in your case change the PhoneContactName as something like the tag etc.,
hope this helps :D
There are 2 things to take care here:
A- make sure that you can call your service method, use [WebMethod] attribute over your function to make it available to be called over http.
you may also need to tune the WebService settings a little to make it to work.
B- Your javascript code is too much for this task.
considering what is written inside the official documentation of Autocomplete, you only need to point out 2 things:
Url of the fetching method,
The control that the user is going to write on, and will trigger the
autocomplete call using the current value inside.
Consider the following example:
$(".tb").autocomplete({source: "URL_OF_YOUR_REMOTE_METHOD"});
considering your example, you will need to put this code:
$(".tb").autocomplete({source: "WebService.asmx/FetchTagList"});
This is the minimal piece of code that you need in order to make it to work.
but to take everything manually as you did, is a little bit complicated and not that easy to figure our problem once they start to happen.
a live example: http://jsfiddle.net/grtWe/1/
just use this piece of code and let me know if it works, then we may go from here to achieve your goal.
if FetchTagList is your webmethod you are calling from jquery then don`t return list from method you can bind datatable directly to the autocomplete textbox just check following link how to do that.
http://nareshkamuni.blogspot.in/2012/06/sample-example-of-jquery-autocomplete.html
also you can do that using ajax autocomplete extender. for using ajax autocomplete extender refer following link
http://www.aspsnippets.com/Articles/ASPNet-AJAX-AutoCompleteExtender-Pass-Additional-Parameter-to-WebMethod-using-ContextKey.aspx
script is as follows:
<script type="text/javascript">
$(document).ready(function () {
SearchText();
});
function SearchText() {
$(".auto").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Photos.aspx/GetAutoCompleteData",
data: "{'CategoryName':'" + document.getElementById("<%= txtCategory.ClientID %>").value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error Occurred");
}
});
}
});
}
</script>
web method:
[WebMethod]
public static List<string> GetAutoCompleteData(string CategoryName)
{
List<string> result = new List<string>();
OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"|DataDirectory|\\ImageDB2.mdb\";Persist Security Info=True");
string query = "select TagName from TAGS where TagName LIKE '%" + CategoryName + "%'";
OleDbCommand cmd = new OleDbCommand(query, con);
con.Open();
//cmd.Parameters.Add("#ptext", System.Data.SqlDbType.NVarChar).Value = CategoryName;
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["TagName"].ToString());
}
return result;
}
C# code
One thing need to remember here, Json data we cannot create manually, create using JavaScriptSerializer Class
<%# WebHandler Language="C#" Class="CountryStateCityHandler" %>
using System;
using System.Web;
using System.Data;
using System.Collections.Generic;
public class CountryStateCityHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
if (context.Request.QueryString["action"] != null)
{
string strCallbackFunf = string.Empty;
if (context.Request.QueryString["callback"] != null)
{
strCallbackFunf = Convert.ToString(context.Request.QueryString["callback"]).Trim();
}
if (context.Request.QueryString["action"] == "getcountry")
{
DataTable dt = GetDataTable("EXEC PR_GetCountries"); //GetDataTable need to write, this method will call the Database and get the result
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
context.Response.ContentType = "text/plain";
if (string.IsNullOrEmpty(strCallbackFunf))
{
context.Response.Write(serializer.Serialize(rows));
}
else
{
context.Response.Write(strCallbackFunf+"("+serializer.Serialize(rows)+");");
}
}
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
//HTML CODE or .aspx code and script needs to be attached.
<html>
<head>
<script src="../scripts/jquery-1.7.js"></script>
<link href="../scripts/jqueryui/development-bundle/themes/smoothness/minified/jquery-ui.min.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="../scripts/jqueryui/js/jquery-ui-1.10.4.custom.min.js"></script>
<link href="../scripts/jqueryui/development-bundle/demos/demos.css" rel="stylesheet" type="text/css" />
<script language="JavaScript" type="text/javascript">
var CountriesTags; //Local variable to store json object
$(function () {
$("#lnkCountry")
.attr("tabIndex", -1)
.attr("title", "Show All Items")
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass("ui-corner-all")
.addClass("custom-combobox-toggle ui-corner-right")
.click(function () {
var wasOpen = $("#Country").autocomplete("widget").is(":visible");
$("#Country").autocomplete("widget").css("display", "none");
if (wasOpen) {
$("#Country").autocomplete("widget").css("display", "none");
return;
}
// Pass empty string as value to search for, displaying all results
$("#Country").autocomplete("search", "");
});
$("#Country").autocomplete({
source: function( request, response) {
var matcher = new RegExp("(^| )" + $.ui.autocomplete.escapeRegex(request.term), "i");
response($.grep(CountriesTags, function (item) {
return matcher.test(item.label);
}));
},
minLength: 0,
select: function (event, ui) {
var sv = ui.item.label;
var res = $.grep(CountriesTags, function (e, i) {
return e.label == sv;
});
if (res.length == 0) {
this.value = "";
$("#CountryID").val("");
alert(sv + " country is not available in database.");
}
else {
$("#CountryID").val(res[0].id);
}
},
change: function (event, ui) {
var sv = this.value;
var res = $.grep(CountriesTags, function (e, i) {
return e.label == sv;
});
if (res.length == 0) {
this.value = "";
$("#CountryID").val("");
alert(sv + " country is not available in database.");
}
else {
$("#CountryID").val(res[0].id);
}
},
});
LoadCountry();
}
//html inputs Value are country id (<%=CountryID %>) and country name (<%=Country%>)
function LoadCountry() {
$.ajax({
url: "CountryStateCityHandler.ashx?action=getcountry",
dataType: "jsonp",
type: 'GET',
async: false,
success: function (data) {
CountriesTags = data;
//array of Json Object will return
//label, value and id are keys
//Example id:219 label:"United States" value:"United States"
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status + ' - Method: Loading countries - ' + thrownError);
}
});
}
</script>
</head>
<body>
<table border="0" cellspacing="0" cellpadding="0">
<tr>
<td>
<input type="text" name="Country" id="Country" maxlength="50" size="20" class="TextBox" value="<%=Country%>" />
<input type="hidden" id="CountryID" name="CountryID" value="<%=CountryID %>">
</td>
<td>
<a style="height: 16px" id="lnkCountry"></a>
</td>
</tr>
</table>
</body>
</html>