ASP.NET page crashes with MySql connection - c#

I am trying to write a dashboard with information about the website's hits and where people come from etc.
I wrote the following page:
<%# Page Language="C#" Inherits="Daschboard.Board" MasterPageFile="~/site.master" %>
<asp:Content id="main" runat="server" ContentPlaceHolderID="main">
<asp:UpdatePanel runat="server" id="updateableWidgets">
<ContentTemplate>
<asp:ContentPlaceHolder id="WidgetsTable">
</asp:ContentPlaceHolder>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
With the following code behind:
using Widgets;
using System;
using System.Text;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Configuration;
using MySql.Data.MySqlClient;
namespace Daschboard
{
public partial class Board : System.Web.UI.Page
{
protected List<IWidget> widgets;
private MySqlConnection db = new MySqlConnection (ConfigurationManager.AppSettings ["mySql"]);
protected void Page_Load(object sender, EventArgs e)
{
widgets = new List<IWidget>();
BuildWidgtTable();
var WidgetThread = new System.Threading.Thread(new System.Threading.ThreadStart(this.InitWidgets));
WidgetThread.Start();
}
private string BuildWidgtTable ()
{
StringBuilder sb = new StringBuilder ();
db.Open ();
var tableName = ConfigurationManager.AppSettings ["DatabaseSiteName"];
var query = "SELECT * FROM " + tableName + ", Widget WHERE " + tableName + ".WidgetID = Widget.WidgetID";
var command = new MySqlCommand (query, db);
var result = command.ExecuteReader ();
while (result.Read()) {
widgets.Add(getWidget(result.GetString(4)));
}
db.Close ();
sb.Append("<table>\n");
sb.Append("</table>");
result.Close();
return sb.ToString();
}
private void InitWidgets ()
{
db.Open();
foreach (var widget in widgets) {
var siteId = ConfigurationManager.AppSettings["siteID"];
var query = "SELECT * FROM Values, Widget WHERE Widget.WidgetID = Values.WidgetID AND SiteID = " + siteId;
var command = new MySqlCommand(query, db);
var result = command.ExecuteReader();
while(result.Read()){
Console.WriteLine(result);
}
result.Close();
widget.Init ("1");
}
db.Close();
}
private IWidget getWidget (string fileName)
{
IWidget widget = null;
switch (fileName) {
case "PageHits":
widget = new PageHits();
break;
case "SiteHits":
widget = new SiteHits();
break;
}
return widget;
}
}
}
When I run this something goes wrong; the debugger stops working without a good error.
It does load the widgets from the database but it doesn't get the values from the database.
I am using Monodevelop on a Mac.

You are running the widget initialization method in a separate thread (InitWidgets method). The page might have already finished rendering when this method executes. If you want to use asynchronous operations in ASP.NET I would recommend you reading about Asynchronous Pages on MSDN. The idea is to mark your WebForm as asynchronous by setting Async="true" in your Page directive (<%# Page Async="true" ... %>) and then use the RegisterAsyncTask method on your web form.

Related

How to display a google bar chart, instead of data table only?

This is asp.net coding website page coding page in here I insert the JavaScript and retrieve data by ID just I set height and weight only
<h1 class="style2"> Channeling Paid and UnPaid Monthly</h1>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<asp:GridView ID="Ch_Data_Monthly" runat="server" BackColor="White"
BorderColor="#3366CC" BorderStyle="None" BorderWidth="1px" CellPadding="4">
</asp:GridView>
<asp:Literal ID="ltScriptsDataMonthly" runat="server"></asp:Literal>
<div id="Ch_BarChart_Monthly" style="width: 900px; height: 300px;" />
This is the C# coding. I'm getting data by SQL Server R2 stored procedure.
i have connecting my data bases by web config called "connectionString"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Text;
using System.Data;
using System.Web.Security;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// Monthly Bind Gridview
Bind_Ch_Data_Monthly();
// Monthly Bind Charts
BindChart_Monthly();
}
}
//Monthly Channeling Paid and UnPaid
private void Bind_Ch_Data_Monthly()
{
Ch_Data_Monthly.DataSource = GetChartDataMonthly();
Ch_Data_Monthly.DataBind();
}
private void BindChart_Monthly()
{
DataTable dsChartDataMonthly = new DataTable();
StringBuilder strScriptDataMonthly = new StringBuilder();
try
{
dsChartDataMonthly = GetChartDataMonthly();
strScriptDataMonthly.Append(#"<script type='text/javascript'>
google.charts.load('visualization', '1', {packages: ['bar']});
google.charts.setOnLoadCallback(drawChart);</script>
<script type='text/javascript'>
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Months', 'Paid', 'UnPaid'],");
foreach (DataRow row in dsChartDataMonthly.Rows)
{
strScriptDataMonthly.Append("['" + row["Months"] + "'," + row["Paid"] + "," + row["UnPaid"] + "],");
}
strScriptDataMonthly.Remove(strScriptDataMonthly.Length - 1, 1);
strScriptDataMonthly.Append("]);");
strScriptDataMonthly.Append("var options = {chart: {title: 'Company Performance',subtitle: 'Sales, Expenses, and Profit: 2014-2017',}};");
strScriptDataMonthly.Append("var chart = new google.charts.Bar(document.getElementById(document.getElementById('Ch_BarChart_Monthly')); chart.draw(data, options); } google.setOnLoadCallback(drawChart)");
strScriptDataMonthly.Append(" </script>");
ltScriptsDataMonthly.Text = strScriptDataMonthly.ToString();
}
catch
{
}
finally
{
dsChartDataMonthly.Dispose();
strScriptDataMonthly.Clear();
}
}
/// <summary>
/// fetch data from mdf file saved in app_data
/// </summary>
/// <returns>DataTable</returns>
private DataTable GetChartDataMonthly()
{
DataSet dsData = new DataSet();
try
{
SqlConnection sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString);
SqlDataAdapter sqlCmd = new SqlDataAdapter("DSB_Ch_MonthWise_Paid&UnPaid", sqlCon);
sqlCmd.SelectCommand.CommandType = CommandType.StoredProcedure;
sqlCon.Open();
sqlCmd.Fill(dsData);
sqlCon.Close();
}
catch
{
throw;
}
return dsData.Tables[0];
}
}
only need one document.getElementById
replace this...
var chart = new google.charts.Bar(document.getElementById(document.getElementById('Ch_BarChart_Monthly')); chart.draw(data, options); } google.setOnLoadCallback(drawChart)
with this...
var chart = new google.charts.Bar(document.getElementById('Ch_BarChart_Monthly')); chart.draw(data, options); } google.setOnLoadCallback(drawChart);
Please fix this line and try
document.getElementById(document.getElementById('Ch_BarChart_Monthly'))
Try this
document.getElementById('Ch_BarChart_Monthly'));
chart.draw(data, options);
google.setOnLoadCallback(drawChart)

Scriptmanager equaivalent required in converting webform to mvc

Basically I have a webform with a scriptmanager and a button to update the results returned from the class webspider (web spider that searches for broken links for a given url). I am trying to convert the code to mvc and have achieved most of this except for the code that is highlighted in bold as I do not have a scriptmanager in the mvc view, can some please give me some pointers on how I can do this, many thanks. -
default.aspx -
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="_check404._Default" %>
<asp:Content runat="server" ID="FeaturedContent" ContentPlaceHolderID="FeaturedContent">
<section class="featured">
<div class="content-wrapper">
<hgroup class="title">
<h1><%: Title %>.</h1>
<h2>Modify this template to jump-start your ASP.NET application.</h2>
</hgroup>
<p>
To learn more about ASP.NET, visit http://asp.net.
The page features <mark>videos, tutorials, and samples</mark> to help you get the most from ASP.NET.
If you have any questions about ASP.NET visit
our forums.
</p>
</div>
</section>
</asp:Content>
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
<h3>Search results:</h3>
<asp:Label ID="lblTot" runat="server" />
<asp:Label runat="server" ID="lblStatus" />
<asp:UpdatePanel runat="server" ID="pnlLinks">
<ContentTemplate> -->
<asp:GridView runat="server" ID="grvLinks" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="NavigateUrl" HeaderText="Url" />
<asp:ButtonField DataTextField="Status" HeaderText="Status" />
</Columns>
</asp:GridView>
<asp:Button runat="server" ID="btnUpdateResults" Text="Update Results" />
</ContentTemplate>
</asp:UpdatePanel>
default.aspx.cs -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using _check404.Spider;
using System.Net;
namespace _check404
{
public partial class _Default : Page
{
private string script = #"setTimeout(""__doPostBack('{0}','')"", 5000);";
private WebSpider WebSpider
{
get { return (WebSpider)(Session["webSpider"] ?? (Session["webSpider"] = new WebSpider())); }
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (!this.WebSpider.IsRunning)
{
string url = "http://bbc.co.uk";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
this.WebSpider.Execute(url);
lblTot.Text = WebSpider.Tot.ToString();
}
//////////////////////////the following code is what I am trying to convert
if (this.WebSpider.IsRunning)
{
this.lblStatus.Text = "Processing...";
ScriptManager.RegisterStartupScript(this, this.GetType(),
this.GetType().Name, string.Format(script, this.btnUpdateResults.ClientID), true);
}
///////////////////////////////////////////////////////////////////////////////////////
this.grvLinks.DataSource = this.WebSpider.Links;
this.grvLinks.DataBind();
}
}
}
spider.cs -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web;
namespace _check404.Spider
{
public class WebSpider
{
public int Tot { get; set; }
const int LIMIT = 10;
string[] invalidTypes = { ".zip", ".doc", ".css", ".pdf", ".xls", ".txt", ".js", ".ico" };
public List<Link> Links;
public bool IsRunning { get; set; }
public WebSpider()
{
this.Links = new List<Link>();
}
public void Execute(string url)
{
this.Links.Clear();
this.Links.Add(new Link() { Status = HttpStatusCode.OK, NavigateUrl = url });
this.IsRunning = true;
WaitCallback item = delegate(object state) { this.FindLinks((UrlState)state); };
ThreadPool.QueueUserWorkItem(item, new UrlState() { Url = url, Level = 0 });
Tot = Links.Count();
}
public void FindLinks(UrlState state)
{
try
{
string html = new WebClient().DownloadString(state.Url);
MatchCollection matches = Regex.Matches(html, "href[ ]*=[ ]*['|\"][^\"'\r\n]*['|\"]");
foreach (Match match in matches)
{
string value = match.Value;
value = Regex.Replace(value, "(href[ ]*=[ ]*')|(href[ ]*=[ ]*\")", string.Empty);
if (value.EndsWith("\"") || value.EndsWith("'"))
value = value.Remove(value.Length - 1, 1);
if (!Regex.Match(value, #"\((.*)\)").Success)
{
if (!value.Contains("http:"))
{
Uri baseUri = new Uri(state.Url);
Uri absoluteUri = new Uri(baseUri, value);
value = absoluteUri.ToString();
}
if (this.Links.Exists(x => x.NavigateUrl.Equals(value))) continue;
try
{
bool validLink = true;
foreach (string invalidType in invalidTypes)
{
string v = value.ToLower();
if (v.EndsWith(invalidType) || v.Contains(string.Format("{0}?", invalidType)))
{
validLink = false;
break;
}
}
if (validLink)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(value);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
this.Links.Add(new Link() { Status = response.StatusCode, NavigateUrl = value });
if (response.StatusCode == HttpStatusCode.OK && state.Level < LIMIT)
{
WaitCallback item = delegate(object s) { FindLinks((UrlState)s); };
ThreadPool.QueueUserWorkItem(
item, new UrlState() { Url = value, Level = state.Level + 1 });
}
}
}
catch
{
this.Links.Add(new Link()
{
Status = HttpStatusCode.ExpectationFailed,
NavigateUrl = value
});
}
}
}
}
catch
{
///
/// If downloading times out, just ignore...
///
}
}
}
}
It looks like you are trying to automatically click a button after 5 seconds if the your spider job is running.
All the script manager is doing is embedding a tag containing your javascript when the markup is generated.
Id say the easiest way to do this is to add an attribute to your model.
class MyModel
{
public bool SpiderRunning { get; set; }
}
Then set this in your controller:
model.SpiderRunning = this.WebSpider.IsRunning
Then in your view, only add the script to the page if this value is true:
#if(Model.SpiderRunning)
{
<script>setTimeout(function(){document.getElementById("btnUpdateResults").click();}, 5000);</script>
}

Master.cs running after the page content codebehind

I have an issue where I am setting session variables using the master page, then using those session variables to deal with content in my placeholder. However, the session variables are not showing as updated in the content. I've made a small example below.
I need the session variables to be updated in both the masterpage and the content. Right now, it's as if the content codebehind is running either before or simultaneous with the masterpage. I assumed that the masterpage codebehind would run first, thus setting the session variables. Any help would be greatly appreciated. Thanks! (.NET 2.0 build using C#)
testmass.master
<%# Master Language="C#" inherits="gpworklist.testmass"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head runat="server">
</head>
<body>
<form id="testthisform">
<select id="test1sel" name="test1" runat="server"></select>
<select id="test2sel" name="test2" runat="server"></select>
<input type="submit" value="Submit" />
</form>
<div id="testsess" runat="server"></div>
<asp:ContentPlaceHolder id="cntnt_phldr" runat="server">
</asp:ContentPlaceHolder>
</body>
</html>
testmass.cs
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
namespace gpworklist
{
public class testmass: MasterPage
{
public string defProv;
public testmass()
{
}
public void Page_Load()
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
Response.Cache.SetExpires(DateTime.MinValue);
HtmlSelect sel1 = (HtmlSelect)this.FindControl("ctl00$test1sel");
HtmlSelect sel2 = (HtmlSelect)this.FindControl("ctl00$test2sel");
HtmlGenericControl div = (HtmlGenericControl)this.FindControl("ctl00$testsess");
string def1;
string def2;
ListItem item;
if (Request["ctl00$test1sel"] != null && Request["ctl00$test1sel"] != "")
{
Session["test1"] = Request["ctl00$test1sel"];
}
if (Request["ctl00$test2sel"] != null && Request["ctl00$test2sel"] != "")
{
Session["test2"] = Request["ctl00$test2sel"];
}
if (Session["test1"] != null)
{
def1 = Session["test1"].ToString();
}
else
{
def1 = "";
}
if (Session["test2"] != null)
{
def2 = Session["test2"].ToString();
}
else
{
def2 = "";
}
for (int i = 0; i <= 10; i++)
{
item = new ListItem(i.ToString(), i.ToString());
if (i.ToString() == def1)
{
item.Selected = true;
}
sel1.Items.Add(item);
}
//Session["test1"] = sel1.Value;
for (int i = 0; i <= 10; i++)
{
item = new ListItem(i.ToString(), i.ToString());
if (i.ToString() == def2)
{
item.Selected = true;
}
sel2.Items.Add(item);
}
Session["test2"] = sel2.Value;
div.InnerHtml = Session["test1"] + " - " + Session["test2"];
}
}
}
testpage.aspx
<%# Page Language="C#" MasterPageFile="testmass.master" Inherits="gpworklist.testpage"%>
<asp:content ID="contentstuff" contentplaceholderid="cntnt_phldr" runat="server">
<div id="testpagesess" runat="server"></div>
</asp:content>
testpage.cs
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
namespace gpworklist
{
public class testpage: Page
{
public testpage()
{
}
public void Page_Load()
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
Response.Cache.SetExpires(DateTime.MinValue);
HtmlGenericControl div = (HtmlGenericControl)this.FindControl("ctl00$cntnt_phldr$testpagesess");
div.InnerHtml = Session["test1"] + " - " + Session["test2"];
}
}
}
A content page's event does fire before the same master page's event.
see http://msdn.microsoft.com/en-us/library/vstudio/dct97kc3(v=vs.100).aspx
You should use the Init event of the MasterPage, instead of the Load event. That will be called before the Page.Load.

How to create multiple divs based on user entered values

I am working on a asp.net project and the main task involved is to generate a image div on button click.
as in retrieving image from database and showing it on screen(another div or table).
How can this task be accomplished?
I will be glad to know how to place an image on button click and then on next button click the next image should appear besides it.
By using the following code you can generate dynamic div's:
HtmlGenericControl div1 = new HtmlGenericControl("div");
Now that you want to show images from database use handler like the following. Make an ashx file, add the code and then take an image control dynamically and bind the output of the image handler to the imageURl property of the image. The code is :
<%# WebHandler Language="C#" Class="DisplayImg" %>
using System;
using System.Web;
using System.Configuration;
using System.IO;
using System.Data;
using System.Data.SqlClient;
public class DisplayImg : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string theID;
if (context.Request.QueryString["id"] != null)
theID = context.Request.QueryString["id"].ToString();
else
throw new ArgumentException("No parameter specified");
context.Response.ContentType = "image/jpeg";
Stream strm = DisplayImage(theID);
byte[] buffer = new byte[2048];
int byteSeq = strm.Read(buffer, 0, 2048);
while (byteSeq > 0)
{
context.Response.OutputStream.Write(buffer, 0, byteSeq);
byteSeq = strm.Read(buffer, 0, 2048);
}
}
public Stream DisplayImage(string theID)
{
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SERVER"].ConnectionString.ToString());
string sql = "SELECT Server_image_icon FROM tbl_ServerMaster WHERE server_Code = #ID";
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#ID", theID);
connection.Open();
object theImg = cmd.ExecuteScalar();
try
{
return new MemoryStream((byte[])theImg);
}
catch
{
return null;
}
finally
{
connection.Close();
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
Just add one line in CS code
UploadImg.ImageUrl = "~/DisplayImg.ashx?id=" + code;
and finally add the image in the div
div1.Controls.Add(YOUR IMAGE's ID);

Understanding Difference between ToArray and JSON

I'm working on jquery to get data bind it to the dropdownlists & also I used web service method, and its working great but I'm not getting some clarification I,e for binding data to one dropdownlist I'm getting data from web method which is returns To Array objects and for another dropdownlist I'm getting data from web method which is returns in terms of JSON object, but in the front end I'm not getting any difference. most of them telling serialised json good method to work on, so what actually happens here? I'm bit confuse
please help me
thank you
**here is my code**
Default.aspx
<html>
<head runat="server">
<title>JsonAndToArray</title>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
ddlActivityType = document.getElementById("<%=ddlActivity.ClientID %>");
$.ajax({
type: "POST",
contentType: "application/json;charset/utf-8",
url: "Visit.asmx/GetActivityByJSON",
dataType: "json",
success: function(results) {
results = eval(results.d);
$('#ddlActivity').get(0).options.length = 0;
$('#ddlActivity').get(0).options[0] = new Option(' --select-- ', '0');
$.each(results, function(val, text) {
$('#ddlActivity').append($('<option></option>').val(text[1]).html(text[0]));
});
}
});
ddlActivityType1 = document.getElementById("<%=ddlActivity2.ClientID %>");
$.ajax({
type: "POST",
contentType: "application/json;charset/utf-8",
url: "Visit.asmx/GetActivity",
dataType: "json",
success: function(results) {
results = eval(results.d);
$('#ddlActivity2').get(0).options.length = 0;
$('#ddlActivity2').get(0).options[0] = new Option('--select--', '0');
$.each(results, function(val, text) {
$('#ddlActivity2').append($('<option></option>').val(text[1]).html(text[0]));
});
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
Json-Activity :
<select id="ddlActivity" runat="server">
</select>
<br />
<br />
ToArray-Activity :
<select id="ddlActivity2" runat="server">
</select>
<br />
<br />
<asp:Button ID="btnJson" runat="server" Text="Json" OnClick="Json_click"/>
</form>
</body>
</html>
Defalut.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.Data.SqlClient;
using System.Web.Script.Serialization;
public partial class Defalut: System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Json_click(object sender,EventArgs e)
{
}
}
**webservices**
**
- Visit.asmx
**
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Data.SqlClient;
using System.Web.Script.Serialization;
using Facade;
/// <summary>
/// Summary description for Visit
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class Visit : System.Web.Services.WebService
{
public Visit()
{
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
[WebMethod]
public IList<string[]> GetActivity()
{
IList<string[]> values = new List<string[]>();
//string value = "";
try
{
SqlConnection con_New = new SqlConnection(#"Data Source=SQLEXPRESS;Initial Catalog="Database";Integrated Security=True;");
con_New.Open();
SqlCommand cmdSelect_ST = new SqlCommand("select id,name from table", con_New);
SqlDataAdapter da_ST = new SqlDataAdapter(cmdSelect_ST);
DataSet ds = new DataSet();
da_ST.Fill(ds);
DataTable dt = ds.Tables[0];
for (int i = 0; i < dt.Rows.Count; i++)
{
string[] ActivityType = new string[2];
ActivityType[0] = dt.Rows[i]["name"].ToString();
ActivityType[1] = dt.Rows[i]["id"].ToString();
values.Add(ActivityType);
}
}
catch (Exception ex)
{
}
return values;
}
[WebMethod]
public string GetActivityByJSON()
{
IList<string[]> values = new List<string[]>();
string value = "";
try
{
SqlConnection con_New = new SqlConnection(#"Data Source=SQLEXPRESS;Initial Catalog="Database";Integrated Security=True;");
con_New.Open();
SqlCommand cmdSelect_ST = new SqlCommand("select name,id from table", con_New);
SqlDataAdapter da_ST = new SqlDataAdapter(cmdSelect_ST);
DataSet ds = new DataSet();
da_ST.Fill(ds);
DataTable dt = ds.Tables[0];
for (int i = 0; i < dt.Rows.Count; i++)
{
string[] ActivityType = new string[2];
ActivityType[0] = dt.Rows[i]["name"].ToString();
ActivityType[1] = dt.Rows[i]["id"].ToString();
values.Add(ActivityType);
}
JavaScriptSerializer js = new JavaScriptSerializer();
value = js.Serialize(values);
}
catch (Exception ex)
{
}
return value;
}
}
In the first call you are returning an array which is converted to a json array by the system. You return this:
IList<string[]> values = new List<string[]>();
In the second call you convert to a jsaon array and return it as a string. Here is the code that does the conversion:
JavaScriptSerializer js = new JavaScriptSerializer();
value = js.Serialize(values);
Since json is just a string formatted in a certain way -- there is no difference. Just when the string to send back is created and who (your code or the system code) creates it.

Categories

Resources