I am trying to load my dynamically generated Datatable during runtime into JS array in javascript. But cannot pass it through webservice as only static methods can be called through javascript.How to return the datatable into javascript.
aspx.cs file :
protected void btnRead_Click(object sender, EventArgs e)
{
//on button click it reads file path of excel and stores it in a string path
}
private DataTable ReadExcelWithStream(string path)
{
//method reads the excel file and stores it in a dt
ForJs(dt);
return dt;
}
[ScriptMethod, WebMethod]
public static DataTable ForJs(DataTable dt)
{
return dt;
}
aspx file :
<script type="text/javascript">
function InsertLabelData() {
PageMethods.ForJs(onSuccess, onFailure);
}
function onSuccess(dt) {
//attach the table to dhtmlx grid
}
But the datatable is not passed to the javascript.
How to pass the datatable to javascript from c# ?
or any other methods to pass the datatable from c# to JS
Please Help.
Thanks!
duplicate?/related question: Dynamically pass datatable from C# to Javascript
You can not simply pass an(y) object to JavaScript. It has to be in a usable format. Like an array or serialized to XML or JSON. Also "DataTables contain lots of additional information which JSON cannot store".
Take a look at how to pass c# datatable to a javascript function or What's the best way to jSON serialize a .NET DataTable in WCF? for more information on this subject.
Related
private void import()
{
DataSet ds = new DataSet();
Export(ds);
}
[WebMethod]
public void Export(DataSet ds)
{
DataSet Ip_ds = new DataSet();
Ip_ds = ds; // insert this data in table
}
You dont need to pass a whole dataset as a parameter in the url .you can just pass the unique identifiers of the dataset as a parameter in the url and then use that identifier to get the required values.
Use HTTP POST method to post the data(Dataset) to the URL. You may need to use Newtonsoft JSON for serializing the Dataset.
I am developing a custom tag for asp.net I want to read data from this tag database and return it as a class object and use it on aspx pages.
My code:
private T RenderControl<T>(Control control)
{
T test = (T)Convert.ChangeType(GetType(DataSource), typeof(T));
test = WebFramework.GetSingleData<T>(SQL, SQLParams.ToArray());
return test;
}
protected override void RenderContents(HtmlTextWriter output)
{
output.AddAttribute(HtmlTextWriterAttribute.Id, this.ID);
}
how can I do that? Example:
<a1:SingleOrDefault ID="test" runat="server" DataSource="MyProject.Models.Members" SQL="SELECT * FROM Members WHERE ID=1"></a1:SingleOrDefault>
<%= test.UserName %>
Thank you.
You could use JSON to convert the object to and from strings, and have your asp.net method work with strings rather than object. JSON can be interpreted in any almost language, server side and client side.
Example:
https://stackoverflow.com/a/2246724/8250558
Netwtonsoft is very popular: https://www.newtonsoft.com/json
I have a datatable containing file paths which I am passing via viewstate (referencing, via a linkbutton, an index in this table), wanting to then use the path from the table to construct a HTTP filetransfer. (So 3 cols; name, path and index)
I am unable to successfully retrieve the datatable once saved in viewstate;
ViewState["varFiles"] = filedata;
(When page is originally constructed, then after postback:)
if (!IsPostBack) { SetupSession(); newpopfiles(); }
else { { if (ViewState["varFiles"] != null) { DataTable filedata = new DataTable(); filedata = (DataTable)Session["varFiles"]; } } }
From what I understand this should pull back filedata as a table in exactly the same form as before postback. Is this correct?
When subsequently referencing the table I get a null reference exception. Any ideas?
Many thanks,
Dan
It sounds like you're almost there, just need to be a bit more consistent with using the same storage mechanism :)
The bit to save the DataTable into your session, probably in OnInit() or PageLoad():
DataTable myDataTable = //... fill it in somehow
Session["varFiles"] = myDataTable;
The bit to read the DataTable after postback:
if (!IsPostBack)
{
SetupSession();
newpopfiles();
}
else
{
DataTable filedata = Session["varFiles"] as DataTable;
if (filedata != null)
{
//... do something
}
}
So, I am dynamically generating jQuery using C# and sending it to the webpage.
The problem is it appears to be generating correct jQuery according to the file and according to Js Fiddle but it does not actually work on the page.
The jsFiddle is here http://jsfiddle.net/ER2hE/
Now I looked up how to send javacript to the website. It should work like this.
http://msdn.microsoft.com/en-us/library/bb359558.aspx
and my code which does that is this method
private void sendScript(string script)
{
const string someScript = "alertMe";
//send the built script to the website.
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), someScript, script, true);
}
This is super simple it has worked for other pieces of code calling. But it has not for this instance.
The code that calls it is this in my C#
private void populateGroups()
{
//this generates correct javascript according to the file and JS fiddle but unfortunately doees not work.
string splitme = "USE ACES SELECT GroupName, GroupID FROM PrimaryGroup ORDER BY GroupName";
DataTable dt = fillDataTable(splitme);
string script = "";
foreach (DataRow dr in dt.Rows)
{
//add the locations to the <select> box
script += " $('#groupList').append('<option value=\" " + dr.ItemArray[1].ToString() + " \"> " + dr.ItemArray[0].ToString() + " </option>'); ";
}
sendScript(script);
JSErrorLog(script, "GROUPS");
}
The whole thing is being called on startup
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack == false)
{
populateMakes();
populateLocation();
populateGroups();
}
}
The jQuery its generating also works in JSFiddle I am pulling this from a method that writes the javascript it generates in a method calling here is the fiddle JSErrorLog.
http://jsfiddle.net/ER2hE/
Oh and my html in my aspx file looks like this
<div class="row2">
<span>Group</span>
<select id="groupList" multiple="multiple" onclick="setGroups()" class="normalsize">
</select>
</div>
I believe that is everything. I just want my stuff to work. I am willing to post any additional code, just ask. If you have an idea as to why its not working, let me know.
When does it actually execute that code? Before or after the element with id "groupList" exists in the DOM? My guess is before.
Solution? Wrap your code inside a document.ready handler.
jQuery(function($) {
$('#groupList').append('<option value=" 46 "> AC Units </option>');
// etc etc
});
Return simple string js code. And run it with eval()
I have this JS function :
var i = 0;
for (i = 0; i < myArray.length; i++) {
alert(myArray[i]);
}
but myArray[] is create on server side with c# :
ArrayList myArray = new ArrayList();
protected void Page_Load(object sender, EventArgs e)
{
foreach (MyObject myobject in MyObjects)
{
myArray.Add(myobject.Description);
}
}
so, how can I "pass" the C# array to Javascript? Or I need to print the whole javascript code on server side and send it to the server?
You can populate javascript array from serverside by using RegisterArrayDeclaration(arrayName, arrayValue) method.
In Cs file
RegisterArrayDeclaration("FavoriteNumbers", "1")
RegisterArrayDeclaration("FavoriteNumbers", "2")
RegisterArrayDeclaration("FavoriteNumbers", "3")
In javascript
<script language="javascript">
<!--
var FavoriteNumbers = new Array(1, 2, 3);
// -->
</script>
You could create json object(array) that would be serialized and sent to client where you can work with it as with Javascript array.
You can use
using System.Web.Script.Serialization;
JavaScriptSerializer serializer = new JavaScriptSerializer();
var output = serializer.Serialize(your_anon_object);
from
System.Web.Extensions.dll
You can serialize your C# array as JSON. You can read in detail about it here.
Also I would suggest using List<> instead of ArrayList.
You can use PageMethods to access functions in your code behind. Simply create a function to access your property.
Example here, http://www.dotnetspider.com/resources/21456-Page-Method.aspx
at before...
1)I will put a hidden in the page...
2) general a string like
"['a','b','c']"
into the hidden at .cs
3) cast to the array from the string at javascript
var arr = eval(hiddenvalue);
4) use it as a array...