How to show full tree from particular parent in javascript with c# - javascript

we are trying to show HierarchyTrees from database without any condition it show's fine.
but when we apply condition for particular user, then showing only root's three child but not showing child's sub child.
i have created one InputBox, by using InputBox i passed the Parent Id with condition, but it showing only three childs not showing full tree .
This is Front end code
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div id="chart">
</div>
<input type="text" id="txtSearch" runat="server" value="t" clientidmode="Static" />
</asp:Content>
This is Javascript code
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["orgchart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
$.ajax({
type: "POST",
url: "WebForm21.aspx/GetChartData",
data: "{'username':'" + document.getElementById('txtSearch').value + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Entity');
data.addColumn('string', 'ParentEntity');
data.addColumn('string', 'ToolTip');
for (var i = 0; i < r.d.length; i++) {
var memberId = r.d[i][0].toString();
var memberName = r.d[i][1];
var sp = r.d[i][3];
var parentId = r.d[i][2].toString() ? r.d[i][2].toString() : '';
data.addRows([[{
v: sp,
f: memberName + '<div><img src = "Pictures/' + memberId + '.jpg" /></div>'
}, parentId, memberName]]);
}
var chart = new google.visualization.OrgChart($("#chart")[0]);
chart.draw(data, { allowHtml: true });
},
failure: function (r) {
alert(r.d);
},
error: function (r) {
alert(r.d);
}
});
}
</script>
This is Backend code
[WebMethod]
public static List<object> GetChartData(string username)
{
string query = "SELECT RegionLoginOID, RegionName, SponserID,Child_Id";
query += " FROM RegionLogin where SponserID LIKE ''+#SponserID+'%' ";
using (SqlConnection con = ClsConnection.Connections())
{
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Parameters.AddWithValue("#SponserID", username);
List<object> chartData = new List<object>();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
chartData.Add(new object[]
{
sdr["RegionLoginOID"], sdr["RegionName"], sdr["SponserID"], sdr["Child_Id"]
});
}
}
return chartData;
}
}
}

Related

ASP.net Textbox Live Search - GridView Results Filter

My scenario is; I'm trying to do a live search feature for my ASP.net project. In the form, I have a description textbox where the user will type in the search and as the user types in anything, the GridView below filters the results accordingly. I have tried this on desktop applications and it's not much of a hassle but I recently dipped in on Web Applications. Any help would be appreciated. I'm sure there is an easy way to do this but I seem to be having trouble finding "that" way.
Below are what I tried already:
I have tried using onTextChanged property of the textbox but it only populates after the event request.
I have added a function using Ajax+ JQuery which calls the method but the gridview is not displaying the data.
enter code here
<script type="text/javascript">
$(function () {
GetCustomers();
});
$("[id*=TxtDescription]").live("keyup", function () {
GetCustomers();
});
function SearchTerm() {
return jQuery.trim($("[id*=TxtDescription]").val());
};
function GetCustomers() {
$.ajax({
type: "POST",
url: "frmDrugMaster.aspx/GetCustomers",
data: '{searchTerm: "' + SearchTerm() + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
}
});
}
var row;
function OnSuccess(response) {
var xmlDoc = $.parseXML(response.d);
var xml = $(xmlDoc);
var customers = xml.find("Drugs");
alert(customers.length);
if (row == null) {
row = $("[id*=gvCustomers] tr:last-child").clone(true);
}
$("[id*=gvCustomers] tr").not($("[id*=gvCustomers] tr:first-child")).remove();
if (customers.length > 0) {
alert(customers.length);
$.each(customers, function () {
var customer = $(this);
$("td", row).eq(0).html($(this).find("DR_Code").text());
$("td", row).eq(1).html($(this).find("DR_Description").text());
$("td", row).eq(2).html($(this).find("DR_UnitDose").text());
alert($("td", row).eq(0).html($(this).find("DR_Description").text()));
$("[id*=gvCustomers]").append(row);
$
row = $("[id*=gvCustomers] tr:last-child").clone(true);
});
} else {
var empty_row = row.clone(true);
$("td:first-child", empty_row).attr("colspan", $("td", row).length);
$("td:first-child", empty_row).attr("align", "center");
$("td:first-child", empty_row).html("No records found for the search criteria.");
$("td", empty_row).not($("td:first-child", empty_row)).remove();
$("[id*=gvCustomers]").append(row);
}
};
</script>
[WebMethod]
public static string GetCustomers(string searchTerm)
{
SqlConnection cn = new SqlConnection(WebConfigurationManager.ConnectionStrings["dbconn"].ConnectionString);
SqlCommand cmd = new SqlCommand("SELECT a.DR_UNITDOSE, a.DR_CODE, a.DR_DESCRIPTION, a.DR_GENERIC1, a.DR_GENERIC2, a.DR_GENERIC3, a.DR_GENERIC4, a.DR_COSTPRICE, a.DR_SELLPRICE, a.DR_STATUS FROM DRUGMASTER a, DRUGCATEGORY b where a.DR_CATEGORY = b.DC_CODE and DR_DESCRIPTION='"+ searchTerm + "' ", cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
DataTable dt = new DataTable();
dt.TableName = "Drugs";
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
DataSet ds = new DataSet();
ds.Tables.Add(dt);
return ds.GetXml();
}
I found a solution to this or atleast a sort to workaround it. I used AJAX + JQuery. I just created a web service for the particular page where the text change will be applied. The codes used are as follows. Hope this helps someone:
/*form*/
create a webform with a textbox and a gridview:
/*Add this script*/
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
script type="text/javascript">
$(function () {
$("[id*=txtCountry]").on("keyup", function () {
$.ajax({
type: "POST",
url: "WebForm2.aspx/GetCustomers",
data: '{searchTerm: "' + $(this).val() + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var row;
var xmlDoc = $.parseXML(response.d);
var xml = $(xmlDoc);
var customers = xml.find("Customers");
if (row == null) {
row = $("[id*=gvCustomers] tr:last-child").clone(true);
}
$("[id*=gvCustomers] tr").not($("[id*=gvCustomers] tr:first-child")).remove();
if (customers.length > 0) {
$.each(customers, function () {
$("td", row).eq(0).html($(this).find("PD_FSTNM").text());
$("td", row).eq(1).html($(this).find("PD_GENDER").text());
$("[id*=gvCustomers]").append(row);
row = $("[id*=gvCustomers] tr:last-child").clone(true);
});
} else {
var empty_row = row.clone(true);
$("td:first-child", empty_row).attr("colspan", $("td", row).length);
$("td:first-child", empty_row).attr("align", "center");
$("td:first-child", empty_row).html("No records found for the search criteria.");
$("td", empty_row).not($("td:first-child", empty_row)).remove();
$("[id*=gvCustomers]").append(empty_row);
}
},
failure: function (response) { alert(response.d); },
});
});
});
</script>
/*C# Code*/
[System.Web.Services.WebMethod]
public static string GetCustomers(string searchTerm = "")
{
string strConnString = ConfigurationManager.ConnectionStrings[""].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
string query = "SELECT * FROM patientdetails";
if (!string.IsNullOrEmpty(searchTerm))
{
query += " WHERE PD_FSTNM LIKE '" + searchTerm + "%'";
}
SqlCommand cmd = new SqlCommand(query, con);
cmd.CommandType = CommandType.Text;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds, "Customers");
return ds.GetXml();
}

how to prevent javascript function to execute when page is postback?

I have this java script code that generate organizational chart from database
<script type="text/javascript">
google.load("visualization", "1", { packages: ["orgchart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
$.ajax({
type: "POST",
url: "add org unit.aspx/GetChartData",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Entity');
data.addColumn('string', 'ParentEntity');
data.addColumn('string', 'ToolTip');
for (var i = 0; i < r.d.length; i++) {
var employeeId = r.d[i][0].toString();
var employeeName = r.d[i][1];
var designation = r.d[i][2];
var reportingManager = r.d[i][3] != null ? r.d[
i][3].toString() : '';
data.addRows([[{
v: employeeId,
f: '<a target="_blank" href="edit emp cv.aspx?employeeId='+employeeId+'">' + employeeName + '</a>' + '<div><span>' + designation + '</div></span>',
}, reportingManager, designation]]);
}
var chart = new google.visualization.OrgChart($("#chart")[0]);
chart.draw(data, { allowHtml: true });
},
failure: function (r) {
alert(r.d);
},
error: function (r) {
alert(r.d);
}
});
}
</script>
and these web method in c# code behind
[WebMethod]
public static List<object> GetChartData()
{
DataLayer.StoreDBEntities dbEntities = new DataLayer.StoreDBEntities();
List<object> chartData = new List<object>();
List<DataLayer.org_unit> result = dbEntities.org_unit.ToList();
foreach (DataLayer.org_unit unit in result)
{
string name = unit.org_unit_type.alias + " " + unit.name;
string Details = "";
if (unit.emp_assignment.ToArray().Length != 0)
{
List<DataLayer.emp_assignment> empAssigns = unit.emp_assignment.ToList();
foreach (DataLayer.emp_assignment assign in empAssigns)
{
Details += assign.job_title.alias + ":" + assign.employee.name + "<br/>";
}
}
chartData.Add(new object[] { unit.id, name, Details, unit.upper_unit_id });
}
return chartData;
}
the chart is regenerated every postback and when page is load
although I did not call java script function at all
how to stop this ? i want to generate chart only whene butten click
First, you need to remove this google.setOnLoadCallback(drawChart); then you can use the jQuery click event like this:
$(function() {
$('#draw-chart').click(function(event) {
event.preventDefault();
drawChart();
});
});
Add a button to your HTML like this:
<button id="draw-chart">Draw Chart</button>

Input array is longer

I try to display data in grid view through web method and jquery function so i try this. I try to display gridview when user select value from drop-down and select dates from calendar
$(function () {
$('[ID*=search_data]').on('click', function () {
var fromdate = $('[ID*=fromdate]').val();
var todate = $('[ID*=todate]').val();
var regiondrop = $('[ID*=regiondrop] option:selected')[0].value;
var GridView1 = $('[ID*=GridView1]');
var obj = {};
obj.fromdate = fromdate;
obj.todate = todate;
obj.regiondrop = regiondrop;
Getdataa(obj);
});
});
function Getdataa(obj) {
//alert('1');
$.ajax({
type: "POST",
url: "WebForm1.aspx/search_data",
data: "{'fromdate':'" + obj.fromdate + "','todate':'" + obj.todate + "','regiondrop':'" + obj.regiondrop + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (result) {
$("#GridView1").empty();
if (result.d.length > 0) {
$("#GridView1").append(
"<tr><th>ID</th><th>OName</th><th>Reg No</th><th>Speed</th></tr>");
for (var i = 0; i < result.d.length; i++) {
$("#GridView1").append("<tr><td>" +
result.d[i].ID+ "</td> <td>" +
result.d[i].OName + "</td> <td>" +
result.d[i].Reg No+ "</td> <td>" +
result.d[i].Speed+ "</td></tr>");
}
}
else {
$("#GridView1").hide();
$("#Label1").text("No Data");
}
},
error: function (error) {
alert("error");
}
});
}
WebMethod
[WebMethod]
public static DataTable search_data(DateTime fromdate, DateTime todate, string regiondrop)
{
try
{
T1 ts = new T1();
var dq = (from vv in ts.tblVe
join rv in ts.tblRe on vv.ID equals rv.ID
join re in ts.tblReg on rv.RID equals re.RID
where
re.Region == regiondrop
&& re.StartDate <= fromdate
&& re.EndDate >= todate
orderby
vv.ID,
rv.OwnerName
select new
{
ID=rv.ID,
OName = rv.OName ,
RegNo = rv.RegNo,
Speed = rv.Speed ,
}).ToList();
DataTable dt = new DataTable();
dt.Rows.Add(dq);
return dt;
}
catch (Exception)
{
throw new Exception();
}
}
in var dq.. dq show this data
[0] = { ID = 1, OName = "Khan", RegNo = "AJ-24",Speed = "124" } [1] = { ID = 2, OName = "Shah", RegNo = "AL-91",Speed = "95" }
UPDATE
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("OName", typeof(string));
dt.Columns.Add("RegNo", typeof(string));
dt.Columns.Add("Speed", typeof(string));
dt.Rows.Add(dq);
return dt;
and exception occur
Unable to cast object of type 'System.Collections.Generic.List`1[<>f__AnonymousType6`5[System.Int32,System.String,System.String,System.String,System.String]]' to type 'System.IConvertible'.Couldn't store <System.Collections.Generic.List`1[<>f__AnonymousType6`5[System.Int32,System.String,System.String,System.String,System.String]]> in ID Column.
You will have to add the columns in you datatable
dt.Columns.Add();
for more information : https://msdn.microsoft.com/en-us/library/hfx3s9wd(v=vs.110).aspx

Organization Chart from sharepoint list items

I want to create an organization chart which I want to populate using the values from a sharepoint list. I would like to retrieve items using REST and Javascript. Here is my code. It in partially working, but cannot create a chart. Please help someone.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["orgchart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
debugger;
$.ajax({
url: "http://myurl/_api/Web/Lists/GetByTitle('Employee Hierarchy')/items",
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
},
success: function (r) {
debugger;
var items = r.d.results;
var data = new google.visualization.DataTable();
data.addColumn('string', 'Entity');
data.addColumn('string', 'ParentEntity');
data.addColumn('string', 'ToolTip');
for (var i = 0; i <items.length; i++) {
var employeeId = r.d[i][0].toString();
var employeeName = r.d[i][1];
var designation = r.d[i][2];
var reportingManager = r.d[i][3] != null ? r.d[i][3].toString() : '';
data.addRows([[{
v: employeeId,
f: employeeName + '<div>(<span>' + designation + '</span>)</div><img src = "Pictures/' + employeeId + '.jpg" />'
}, reportingManager, designation]]);
var chart = new google.visualization.OrgChart($("#chart")[0]);
chart.draw(data, { allowHtml: true });
},
failure: function (r) {
alert(r.d);
},
error: function (r) {
alert(r.d);
}
});
}
</script>
<div id="chart">
</div>
this is the structure of my sharepoint list
The following example demonstrates how to visualize SharePoint List data as organization chart via Google Visualization API
google.load("visualization", "1", { packages: ["orgchart"] });
google.setOnLoadCallback(displayChart);
function displayChart()
{
loadListItems('Employee Hierarchy')
.done(function(data){
var items = data.d.results;
drawChart(items);
})
.fail(function(error){
console.log(error);
});
}
function drawChart(items) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('string', 'Manager');
data.addColumn('string', 'ToolTip');
for (var i = 0; i < items.length; i++) {
data.addRow([items[i]['Title'],items[i]['Manager']['Title'],'']);
}
var chart = new google.visualization.OrgChart(document.getElementById('chart_div'));
chart.draw(data, { allowHtml: true });
}
function loadListItems(listTitle){
return $.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists/GetByTitle('" + listTitle + "')/items?$select=Title,Manager/Title&$expand=Manager",
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
}
});
}
Key points
In my example the list has the following schema:
Field Name Type
Title Text
Manager Lookup
Description Note
List view page
Resulting page

Binding Kendo Data Source with Async $.ajax calling from C# MVC Controller Action

This is my action in controller. Which return a List> converting into DataSourceResult.and also Serializing into Json.
[HttpPost]
public ActionResult GetMissingShiftData([DataSourceRequest]DataSourceRequest request)
{
DataTable dtResponse = new DataTable();
var dynamicList = new List<dynamic>();
var myMainList = new List<List<dynamic>>();
List<DataSourceResult> viewResultList = new List<DataSourceResult>();
string RigNumber = string.IsNullOrWhiteSpace( resultData.Filter.SelectedRig.RigNumber) || resultData.Filter.SelectedRig.RigNumber == "ALL" ? "" : resultData.Filter.SelectedRig.RigNumber;
DataSet response = MissingShiftsReportData.GetData(Convert.ToDateTime(resultData.Filter.DateStart), Convert.ToDateTime(resultData.Filter.DateEnd), ConnString, RigNumber);
foreach (DataTable dt in response.Tables)
{
dtResponse = dt;
string[] columnNames = dtResponse.Columns.Cast<DataColumn>().Select(x => x.ColumnName).ToArray();
foreach (DataRow dr in dtResponse.Rows)
{
dynamic myObj = new ExpandoObject();
var p = myObj as IDictionary<string, object>;
Regex rgx = new Regex("[^a-zA-Z0-9]");
for (int i = 0; i < columnNames.Length; i++)
{
string name = dr.Table.Columns[i].ColumnName.Replace(" ", String.Empty);
name = name.Replace(".", String.Empty);
name = name.Replace("(", String.Empty);
name = name.Replace(")", String.Empty);
name = rgx.Replace(name, "");
p[name] = dr[i];
}
dynamicList.Add(p);
}
myMainList.Add(dynamicList);
}
DataSourceResult viewResult = myMainList.ToDataSourceResult(request);
string JsonViewData = JsonConvert.SerializeObject(viewResult.Data);
return new ContentResult { Content = JsonViewData, ContentType = "application/json", ContentEncoding = Encoding.UTF8 };
}
And this is the async call I am doing with Jqery.while I am trying to bind a data source it shows "data[0].Data" is "undefined". How can I make use of 'data'.
$.ajax({
url: "GetMissingShiftData",
type: "post",
datatype: 'json',
success: function (data) {
var list = data[0].Data;
var dataSource = new kendo.data.DataSource({
data: data[0].Data
});
dataSource.read();
return false;
},
error: function (msg) {
toastr.error("Error: " + msg.statusText);
}
});
You are serializing an array (the Data property) and don't need to use the Data field at the client-side:
$.ajax({
url: "GetMissingShiftData",
type: "post",
datatype: 'json',
success: function (data) {
var dataSource = new kendo.data.DataSource({
data: data
});
dataSource.read();
return false;
},
error: function (msg) {
toastr.error("Error: " + msg.statusText);
}
});

Categories