I am developing a web application using asp.net c# and using MS SQL as database. In my application I want to plot a graph of mothly sales. For doing that I found very nice jquery plugin called flot.
But the problem is that I dont know how to pass my sql data to flot. I've a table which has two columns date (DateTime) and number of sales (int). I want the number of sales on y axis and date on x axis.
I googled alot around the web, but I didn't find much help about how to pass MS SQL data to flot.
Please any one can help me to do so.
Thanks in advance.
here is demo code
in code behind
public class chartdata
{
public string Date { get; set; }
public int Sales { get; set; }
}
[System.Web.Services.WebMethod]//public static web method in code behind
public static List<chartdata> GetData() //int StartRowindex,
{
List<chartdata> myResult= new List<chartdata>();
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["demo"].ConnectionString))
{
//string sqlString = "SelectbyYearTotalProductAssign";
string sqlString = "SelectbyYearTotalProductAssign1";
using (SqlCommand cmd = new SqlCommand(sqlString, conn))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (rdr.Read())
{
chartdata obj = new chartdata();
obj.Sales = Convert.ToInt32(rdr["Sales"]);
obj.Date = rdr["Date"].ToString();
myResult.Add(obj);
}
conn.Close();
}
}
return myResult;
}
your html
<div id="chart1"></div>
<script language="javascript" type="text/javascript">
jQuery(document).ready(function () {
DrowChart();
});
function DrowChart() {
jQuery("#chart1").html('');
var list12 = [];
jQuery.ajax({
type: "POST",
url: "Default.aspx/GetData",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
data: "{}",
success: function (data) {
jQuery.map(data.d, function (item) {
var list = [];
list.push("'" + item.Date + "'");
list.push(item.Sales);
list12.push(list);
});
var plot1 = jQuery.jqplot('chart1', [list12],
{
seriesDefaults: {
// Make this a pie chart.
renderer: jQuery.jqplot.PieRenderer,
rendererOptions: {
// Put data labels on the pie slices.
// By default, labels show the percentage of the slice.
showDataLabels: true
}
},
legend: { show: true, location: 'e' }
}
);
}
});
}
</script>
<script type="text/javascript" src="chartLib/jquery.jqplot.min.js"></script>
<script type="text/javascript" src="chartLib/plugins/jqplot.barRenderer.min.js"></script>
<script type="text/javascript" src="chartLib/plugins/jqplot.pieRenderer.min.js"></script>
<script type="text/javascript" src="chartLib/plugins/jqplot.categoryAxisRenderer.min.js"></script>
<script type="text/javascript" src="chartLib/plugins/jqplot.pointLabels.min.js"></script>
<link rel="stylesheet" type="text/css" href="chartLib/jquery.jqplot.min.css" />
You could use a jQuery Ajax call to get your flot data from server-side in JSON format. If successful then parse the JSON object and call $.plot using your placeholder div, the parsed JSON result, and any options.
Related
I am currently trying to pass data from a controller to a view to display a pie Chart. But instead of a Pie Chart the webpage is only displaying the string as shown below. How can I get this to show the Pie Chart and not the string
Controller Code
c#
public ActionResult Index()
{
return Json(Result(), "text/plain",JsonRequestBehavior.AllowGet);
}
View Code
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/x-www-form-urlencoded;charset=utf-8; charset = utf - 8",
cache: false,
url: '#Url.Action("Index", "Home")',
success: function (result) {
console.log(result);
google.charts.load('current', {
'packages': ['corechart']
});
google.charts.setOnLoadCallback(function () {
drawChart(result);
});
}
});
});
function drawChart(result) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('number', 'Marks Obtained');
var dataArray = [];
$.each(result, function (i, obj) {
dataArray.push([obj.stdName, obj.marksObtained]);
});
data.addRows(dataArray);
var columnChartOptions = {
title: "Students Performance",
width: 1000,
height: 400,
bar: { groupWidth: "20%" },
};
var columnChart = new google.visualization.PieChart(document
.getElementById('piechart_div'));
columnChart.draw(data, columnChartOptions);
}
</script>
</head>
<body>
<div id="piechart_div"></div>
The strange thing is that I downloaded an example, which works fine, and I set up a new MCV project and added the code exactly the same, but my project shows the string, while the project I downloaded will display the pie chart with no problems. I am really confused as to why this is happening
I'm working on an ASP.Net C# Google Charts internal reporting site but am having trouble getting the chart to display. Code seems to run fine and allows me to run in debug.
I can get to the ASP page, but there is no chart present.
EDIT: Initial issue was down to misplaced ], how silly of me!
I'm now faced with the following in the Browser Console, can any help?
A Parser-blocking, cross site (i.e. different eTLD+1) script,
https://www.google.com/uds/?file=visualization&v=1&packages=corechart,
is invoked via document.write. The network request for this script MAY
be blocked by the browser in this or a future page load due to poor
network connectivity. If blocked in this page load, it will be
confirmed in a subsequent console message.See
https://www.chromestatus.com/feature/5718547946799104 for more details
.
Code below;
ASP Page:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master"
AutoEventWireup="true" CodeBehind="ADMReports.aspx.cs"
Inherits="ADMReports.ADMReports" %>
<%# Register Assembly="ADMReports" Namespace="ADMReports" TagPrefix="asp" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
</head>
<body>
<div id="b_sale" style="width:500px; height:300px;">
TEST
</div>
</body>
<script>
// VISUALIZATION API.
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(createPIE);
function createPIE() {
// SET CHART OPTIONS.
var options = {
title: 'Total Invoices Per Month',
colors: ['#888', 'orange'],
is3D: true
};
$.ajax({
url: "ADMReports.aspx",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
var arrValues = [['Year', 'Month', 'OrdersProcessed']]; // DEFINE AN ARRAY.
var iCnt = 0;
$.each(data.d, function () {
// POPULATE ARRAY WITH THE EXTRACTED DATA.
arrValues.push([data.d[iCnt].Year, data.d[iCnt].Month], data.d[iCnt].OrdersProcessed]);
iCnt += 1;
});
var figures = google.visualization.arrayToDataTable(arrValues)
var chart = new google.visualization.PieChart(document.getElementById('b_sale'));
chart.draw(figures, options);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('Got an Error');
}
});
}
</script>
</html>
Code behind asp page
I will be amending the SQL query to pull from a Stored Procedure, but kept it simple for testing purposes.
public partial class ADMReports : System.Web.UI.Page
{
private string Year;
private string Month;
private int OrdersProcessed;
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public List<ADMReports> Total_Invoices()
{
List<ADMReports> Invoices = new List<ADMReports>();
string sConnString = "Data Source=<servername>;Initial Catalog=<DB>;Integrated Security=True";
SqlConnection myConn = new SqlConnection(sConnString);
SqlCommand objComm = new SqlCommand("SELECT YEAR(DateTimeScanned) AS Year, MONTH(DateTimeScanned) AS Month, COUNT(OrderNumber) AS OrdersProcessed FROM tabTrace WHERE YEAR(DateTimeScanned) = YEAR(GETDATE()) GROUP BY MONTH(DateTimeScanned), YEAR(DateTimeScanned) ORDER BY MONTH ASC ", myConn);
myConn.Open();
SqlDataReader sdr = objComm.ExecuteReader();
while (sdr.Read())
{
ADMReports objValues = new ADMReports();
objValues.Year = sdr["Year"].ToString();
objValues.Month = sdr["Month"].ToString();
objValues.OrdersProcessed = (int)sdr["OrdersProcessed"];
Invoices.Add(objValues);
}
myConn.Close();
sdr.Close();
return Invoices;
}
}
I would strongly recommend to add all related scripts in local project and remove links to third-party references eg. google in this case. This will help in reducing load time for page also you will not be surprised with random updates of such scripts which are hosted on other server.
I am trying to pass HiddenField value to WebMethod GetAutoCompleteData to enable auto complete in text box based on selected search field.
I have tried pass HiddenField values using code-behind, but it didn't work.
There is no issues with javascript codes.
Note: I have tried to use HiddenField value in another method, and it worked, so I am sure that HiddenField is taking values using JavaScript code.
Code-behind:
public static string hdnvalue { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
hdnvalue = hdnSearchParam.Value;
}
[WebMethod]
public static List<string> GetAutoCompleteData(string value)
{
string hiddenfiedlvalue = hdnvalue;
List<string> result = new List<string>();
string strConnString = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlCommand cmd = new SqlCommand("select #hiddenfiedlvalue from Users where #hiddenfiedlvalue LIKE '%'+#SearchText+'%'", con))
{
con.Open();
cmd.Parameters.AddWithValue("#SearchText", value);
cmd.Parameters.AddWithValue("#hiddenfiedlvalue", hiddenfiedlvalue);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(string.Format("{0}", hiddenfiedlvalue));
}
return result;
}
}
}
Code used to pass selected values from drop-down menu to HiddenField:
<script type="text/javascript">
$(document).ready(function (e) {
$('.search-panel .dropdown-menu').find('a').click(function (e) {
e.preventDefault();
var param = $(this).attr("href").replace("#", "");
var concept = $(this).text();
$('.search-panel span#search_concept').text(concept);
$('[id$=hdnSearchParam]').val(param);
});
});
</script>
Auto complete code:
<script type="text/javascript">
$(function () {
SearchText();
});
function SearchText() {
$(".autosuggest").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/GetAutoCompleteData",
data: "{'value':'" + $('#txtSearch').val() + "'}",
dataType: "json",
success: function (data) {
if (data.d.length > 0) {
response($.map(data.d, function (item) {
return {
label: item.split('/')[0],
val: item.split('/')[1]
}
}));
}
else {
response([{ label: 'No Records Found', val: -1 }]);
}
},
error: function (result) {
alert("Error");
}
});
},
});
}
</script>
ASPX:
<asp:HiddenField ID="hdnSearchParam" runat="server" />
<div class="col-xs-8">
<div class="input-group">
<div class="input-group-btn search-panel">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
<span id="search_concept">Filter by</span> <span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu">
<li>User ID</li>
<li>User Type</li>
<li>User Name</li>
<li>First Name</li>
<li>Last Name</li>
<li>Email</li>
</ul>
</div>
<input type="hidden" name="search_param" value="all" id="search_param">
<asp:TextBox ID="txtSearch" CssClass="autosuggest form-control" runat="server"></asp:TextBox>
<span class="input-group-btn"></span>
</div>
</div>
Your page has several issues.
First, why are you using a hidden field for this? Why don't you just pass the dropdown value as a second parameter in the Ajax request?
Second, in your code behind you are reading the hidden value only on page load, and that value is never updated with each Ajax request (Page_Load is not executed again). You made that static trick with hdnvalue just to make it compile, but it won't work. Also, making it static makes it be shared among all web clients using that page!
Third, why are you storing the dropdown value in its href as well? You could use a span or even simple text instead.
Fourth, you are using the server controls markup ID instead of the ClientID, which may be different depending on the .NET framework you are using. Better play safe and use ClientID always.
Fifth, if with jQuery you select by ID, just use the ID, there's no need to use any other class selectors. Of course, you should never have repeated IDs!
Sixth, you can't use parameterized variables as column names. You must use a dynamic query. More info about that here. Also the reader wasn't working properly (only adding the hidden field) and it's better to enclose the ExecuteReader in a using block.
Summarizing, use this:
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static List<string> GetAutoCompleteData(string value, string filterBy)
{
string strConnString = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
con.Open();
string command = string.Format("select {0} from Users where {0} LIKE '%'+#SearchText+'%'", filterBy);
using (SqlCommand cmd = new SqlCommand(command, con))
{
cmd.Parameters.AddWithValue("#SearchText", value);
using (SqlDataReader dr = cmd.ExecuteReader())
{
List<string> result = new List<string>();
while (dr.Read())
{
result.Add(dr.GetString(0));
}
return result;
}
}
}
}
<script type="text/javascript">
$(document).ready(function (e) {
$('.search-panel .dropdown-menu').find('a').click(function (e) {
e.preventDefault();
var concept = $(this).text();
$('#search_concept').text(concept);
});
});
</script>
Important: if you are afraid of SQL Injection, you may want to do some validation with filterBy first.
In your Javascript, fix this line only:
data: "{'value':'" + $('#<%= txtSearch.ClientID %>').val() + "','filterBy':'" + $('#search_concept').text() + "'}",
Finally, just get rid of both hidden fields (user control and html control).
try to change data parameter to this:
data: "{'value':'" + $('#hdnSearchParam').val() + "'}",
Try removing the dollar sign from this line of code.
$('[id$=hdnSearchParam]').val(param);
It should be smthing like this:
$('[ID="hdnSearchParam"]').val(param);
I want to create a tagging system for my website which allows user to enter the required skills,separated by comma, using ASP.net and C#.
In detail:
A textbox will receive tags, separated by comma.
Suggestions will be provided while typing, based on AVAILABLE tags in my database.
Suggested tags will be displayed, below the textbox.
If a new tag is encountered, it is inserted into database.
The tags (separated by comma), given by the user could be further manipulated according to my needs (a way of doing that).
I want to make a separate entry for each and every tag into the database.
I tried using Tag-it by Levy Carneiro Jr.. it is working perfect for local source.
But when I tried attaching it with my database using this. It just doesn't work.
My code:-
<script type="text/javascript">
$(document).ready(function () {
SearchText();
});
function SearchText() {
$(".autosuggest").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "tag.aspx/GetAutoCompleteData",
data: "{'username':'" + document.getElementById('singleFieldTags2').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
<script>
$(function () {
//Local sample- //var sampleTags = ['c++', 'java', 'php', 'coldfusion', 'javascript', 'asp', 'ruby', 'python', 'c', 'scala', 'groovy', 'haskell', 'perl', 'erlang', 'apl', 'cobol', 'go', 'lua'];
$('#singleFieldTags2').tagit({
});
});
</script>
<body>
<form id="form1" runat="server">
<asp:TextBox name="tags" id="singleFieldTags2" value="Apple, Orange" class="autosuggest" runat="server"></asp:TextBox>
</form>
Backend C# code-
[WebMethod]
public static List<string> GetAutoCompleteData(string username)
{
List<string> result = new List<string>();
using (SqlConnection con = new SqlConnection("Data Source=ZESTER-PC;Initial Catalog=mystp;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand("select tag_name from tags where tag_name LIKE '%'+#SearchText+'%'", con))
{
con.Open();
cmd.Parameters.AddWithValue("#SearchText", username);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["tag_name"].ToString());
}
return result;
}
}
}
Here tags is my tag table containing tag_id and tag_name.
I have created the Tagging System using ASP.net
Check it out.. nd do rate it..
Tagging System using ASP.net by Sumanyu Soniwal
I am trying to build an autocomplete, but I have troubles patching along the parts.
First, my view include this field:
<p>#Html.TextBoxFor(_item => _item.mCardName, Model.mCardName, new { #class = "cardText", id = "card_name"} ) </p>
Very simple. Next, the javascript call:
<script type="text/javascript">
$(function() {
$('#card_name').autocomplete({
minlength: 5,
source: "#Url.Action("ListNames", "Card")",
select: function (event, ui) {
$('#card_name').text(ui.item.value);
},
});
});
</script>
Which calls this method:
public ActionResult ListNames(string _term)
{
using (BlueBerry_MTGEntities db = new BlueBerry_MTGEntities())
{
db.Database.Connection.Open();
var results = (from c in db.CARD
where c.CARD_NAME.ToLower().StartsWith(_term.ToLower())
select new {c.CARD_NAME}).Distinct().ToList();
JsonResult result = Json(results.ToList(), JsonRequestBehavior.AllowGet);
return Json(result, JsonRequestBehavior.AllowGet);
}
}
If i insert the "Power" word, the JSON data is posted back like this:
{"ContentEncoding":null,"ContentType":null,"Data":[{"CARD_NAME":"Power Armor"},{"CARD_NAME":"Power Armor (Foil)"},{"CARD_NAME":"Power Artifact"},{"CARD_NAME":"Power Conduit"},{"CARD_NAME":"Power Conduit (Foil)"},{"CARD_NAME":"Power Leak"},{"CARD_NAME":"Power Matrix"},{"CARD_NAME":"Power Matrix (Foil)"},{"CARD_NAME":"Power of Fire"},{"CARD_NAME":"Power of Fire (Foil)"},{"CARD_NAME":"Power Sink"},{"CARD_NAME":"Power Sink (Foil)"},{"CARD_NAME":"Power Surge"},{"CARD_NAME":"Power Taint"},{"CARD_NAME":"Powerleech"},{"CARD_NAME":"Powerstone Minefield"},{"CARD_NAME":"Powerstone Minefield (Foil)"}],"JsonRequestBehavior":0,"MaxJsonLength":null,"RecursionLimit":null}
For reference purpose, here are two of the scripts that run:
<script src="/Scripts/jquery-2.0.3.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
However nothing is displayed. I would have liked to see the results displayed like a normal autocomplete would do. Can anyone help me out making things work?
EDIT
I have been working on this for a while. I have posted up there the new javascript, controller method and results obtained. But the thing still does not work and I would appreciate any help.
for autocompletes, i use the javascriptserializer class. the code goes something like this.
My.Response.ContentType = "application/json"
Dim serializer As JavaScriptSerializer = New JavaScriptSerializer
Dim dt As DataTable = GetDataTable("proc_name", My.Request.QueryString("term"))
Dim orgArray As ArrayList = New ArrayList
For Each row As DataRow In dt.Rows
Dim thisorg As New thisOrg
thisorg.id = row("organization_child_id")
thisorg.value = row("organization_name")
orgArray.Add(thisorg)
Next
My.Response.Write(serializer.Serialize(orgArray))
Public Class thisOrg
Public id As Integer
Public value As String
End Class
basically just takes a datatable, adds a series of objects to the array, then serializes it.
Finally! After taking a break, I got my answer.
See this?
public ActionResult ListNames(string _term)
{
using (BlueBerry_MTGEntities db = new BlueBerry_MTGEntities())
{
db.Database.Connection.Open();
var results = (from c in db.CARD
where c.CARD_NAME.ToLower().StartsWith(_term.ToLower())
select new {c.CARD_NAME}).Distinct().ToList();
JsonResult result = Json(results.ToList(), JsonRequestBehavior.AllowGet);
return Json(result, JsonRequestBehavior.AllowGet);
}
}
As it happens, I was building a Json object OF another Json object. So that's why the data was not passed properly.
I've rebuilt the method, made it work, and refined it like this:
public JsonResult ListCardNames(string term)
{
using (BlueBerry_MagicEntities db = new BlueBerry_MagicEntities())
{
db.Database.Connection.Open();
var results = from cards in db.V_ITEM_LISTING
where cards.CARD_NAME.ToLower().StartsWith(term.ToLower())
select cards.CARD_NAME + " - " + cards.CARD_SET_NAME;
JsonResult result = Json(results.ToList(), JsonRequestBehavior.AllowGet);
return result;
}
And my javascript action:
<script type="text/javascript">
$(function() {
$('#searchBox').autocomplete({
source: function(request, response) {
$.ajax({
url: "#Url.Action("ListCardNames")",
type: "GET",
dataType: "json",
data: { term: request.term },
success: function(data) {
response($.map(data, function(item) {
return { label: item, value1: item };
}));
}
});
},
select:
function(event, ui) {
$('#searchBox').val(ui.item);
$('#cardNameValue').val(ui.item);
return false;
},
minLength: 4
});
});
</script>
And now everything works like a charm.