Call C# code behind function from jstorage - c#

I am using the below code to store data using jstorage. i can;t understand what is load_data_from_server(). Please help me to call a code behind function from jstorage
<script src="prototype.js"></script>
<script src="jstorage.js"></script>
<script>
// Check if "key" exists in the storage
var value = $.jStorage.get("key");
if(!value){
// if not - load the data from the server
value = "hai";
value = load_data_from_server() //I want to call c# code behind function here
// and save it
$.jStorage.set("key",value);
}
</script>

Related

Using a C# list in a javascript snippet

I want to use two arrays from C# in the JS snippet in a view. In order to do so I've tried to use the JavaScriptSerializer() but the data array isn't getting any values (the view's source shows it as follows):
var mydata =
Every example I've come across injects the C# code in JS by using <%=%> tags. This doesn't yield any results for me since I'm using ASP.NET MVC 4. Therefore I tried it with the following:
<script type="text/javascript">
var mydata = #{ new JavaScriptSerializer().Serialize(Model.GetData());}
$(function () {
// Generates a chart using the mydata array
}
</script>
What's wrong about this syntax? When I try to add an array for the headers underneath it, I receive a compilation error. There are warnings that the lines aren't terminated, but when I add ; at the end of each line it gives a syntax error as well (no specific error, just 'syntax error').
The data in GetData() and GetHeaders() are defined as such:
public List<int> GetData() {
return new List<int>(new[] { 4, 5, 6});
}
I've tried returning it as a int[] but this made no difference.
How can I use a C# list/array in a JavaScript snippet?
Edit: image of the unknown compilation error.
When I don't place the semicolons I get a syntax error on the second var. I get a suggestion to terminate the line endings, which adds the semicolons to the end. Then I have the issue as shown below. Curious detail: there are no red bars to the side of the file that usually indicate where the error is located.
That being said: when executing the script, the arrays have their expected values and everything works as it should.
The problem is that #{ } creates a block of code, it doesn't print the result to the rendered page. You can do this:
#{
var serializer = new JavaScriptSerializer();
#serializer.Serialize(Model.GetData())
}
Or even better, use the Json helper:
#Json.Encode(Model.GetData())
When you enclose operations within code blocks the output won't be rendered unless you explicitly tells it to render.
Try this one:
#Html.Raw(Json.Encode(Model.GetData()))
Try to put the result of the serializer in single quotes, like:
<script type="text/javascript">
var data = '#{ new JavaScriptSerializer().Serialize(Model.GetData());}';
</script>
You can create a HTML helper to call this, example:
<script type="text/javascript">
var data = '#Html.JSSerializerHelper(Model.GetData())';
</script>
Only one way that I think most elegant.
You could convert your List into JavaScript array to use within js.
Try this:
<script type="text/javascript">
var mydata = [];
#foreach(int i in Model.GetData()) {
<text>mydata.push(#i);</text>
}
$(function () {
// Generates a chart using the mydata array
}
</script>

Javascript Com array Component giving me wrong array values

I try to create COM Component for C# method and then try to access this method using javascript.
I have run GACUtil -i and Regasm /Codebase command for create share assembly and also register into Registry successfully.
This is my C# Method that return an int[] array for this I create an COM Component for this method.
nChannelsCount = 15 which is use in for loop
[Guid("4794D615-BE51-4a1e-B1BA-453F6E9337C4")]
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
[ComSourceInterfaces(typeof(IComOjbect))]
public class MyComObject : IComOjbect
{
}
[Guid("4B3AE7D8-FB6A-4558-8A96-BF82B54F329C")]
[ComVisible(true)]
public interface IComOjbect
{
[DispId(0x10000009)]
int[] GetData(int index);
}
But when I access this method in javascript it gives me and just count of 15 but I want 5500 count that show in Quick Watch. I dont know how to do this in javascript to achive this code but still i try this javascript code as below
<html>
<head>
<title>My Com Component</title>
<object id="myComComponent" name="myComComponent" classid="clsid:4794D615-BE51-4A1E-B1BA-453F6E9337C4">
</object>
<script language="javascript" type="text/javascript">
function MyComComponent_onload()
{
try {
var nAllData = [];
for (var index = 0; index < 15; index++)
{
nAllData.push(myComComponent.GetData(index));
}
alert(nAllData.length);
}
catch (err) {
alert(err.message);
}
}
</script>
</head>
<body onload="MyComComponent_onload();" onunload="MyComComponent_onunload();">
</body>
</html>
GetData returns an array. The JavaScript code calls it 15 times, and every time pushes the result onto yet another array, called nAllData (the fact that the variable name in JavaScript is the same as in C# is irrelevant - they are unrelated). As a result, you have an array of 15 elements, where each of those elements is in turn an array (presumably of 5500 elements - whatever GetData returns).
The loop within GetData implementation is pointless - the function returns on the very first iteration through that loop. It's not clear what you were trying to achieve there.
Finally, I don't believe JavaScript can directly consume safearrays (which is how I believe the return value of GetData ends up being represented by COM interop). Try this:
var data = new VBArray(myComComponent.GetData(index)).toArray();
alert(data.length);
nAllData.push(data);

Why can't i run a javascript function from c# code?

This is a part of the C# code where i want to insert the network graph:
DetailsBody3.Text = "<tr class=\"space\">";
DetailsBody3.Text += "<td>" + "<div id=\"center-container\"><div id=\"infovis\"></div> />";
DetailsBody3.Text += "</div></td>";
DetailsBody3.Text += "</tr>";
In the "infovis" div in the graph code, the graph exists.
And in the graph javascript file:
function init1(){
// init data
}
var fd = new $jit.ForceDirected({
//id of the visualization container
injectInto: 'infovis',
// some other code,
}
I want to call the int1() function and draw the graph in the table created in C# above.
Javascript code runs in the browser. Your ASP.Net C# code runs in the server.
What you actually want to do is add this to the section of your your .aspx file:
<script type="text/javascript">
$(document).ready(
function(){
init();
}
);
</script>
This will call your javascript init() method once the page has loaded.
Try...
Page thisPage = HttpContext.Current.Handler as Page;
if (!thisPage.ClientScript.IsStartupScriptRegistered("run_init1")) {
thisPage.ClientScript.RegisterStartupScript(
thisPage.GetType(),
"run_init1",
"init1();",
true);
}
The above may need to be adjusted a bit depending on what version of the .Net Framework you are using (this works with version 4.0).

Microsoft JScript runtime error: 'null' is null or not an object

I have application like where i can create dynamic tabs. and delete cross bar option on tabs. When I am trying to delete the tab I am getting error like
Microsoft JScript runtime error: 'null' is null or not an object and point to my Javascript code.
Here is my JS code.
<script type="text/javascript">
/* <![CDATA[ */
function deleteTab(tabText)
{
var tabStrip = $find("<%= RadTabStrip1.ClientID %>");
var multiPage = $find("<%= RadMultiPage1.ClientID %>");
var tab = tabStrip.findTabByText(tabText);
var pageView = tab.get_pageView();
var tabToSelect = tab.get_nextTab();
if (!tabToSelect)
tabToSelect = tab.get_previousTab();
tabStrip.get_tabs().remove(tab);
multiPage.get_pageViews().remove(pageView);
if (tabToSelect)
tabToSelect.set_selected(true);
}
/* ]]> */
</script>
and in page lode
if (!Page.IsPostBack)
{
RadTab tab = new RadTab();
tab.Text = string.Format("New Page {0}", 1);
RadTabStrip1.Tabs.Add(tab);
RadPageView pageView = new RadPageView();
pageView.Height = new Unit("50px");
pageView.Width = new Unit("1300px");
RadMultiPage1.PageViews.Add(pageView);
BuildPageViewContents(pageView, RadTabStrip1.Tabs.Count);
RadTabStrip1.SelectedIndex = 0;
}
This error can occur if you are trying to use an object which is null. In that code quite a lot of things can return null: $find, findTabByText, getPageView, get_nextTab, get_previousTab etc. I suggest you alert() everything before using it. That way you will find what is null.
You're not checking any of those function calls to see if they're actually returning something. One of them is returning null, but your code does not notice that and tries to use the result in a subsequent statement.
Try this in Firefox with Firebug and you'll probably get better error messages.
$find can return null if you are trying to call it too early. Remember that ASP.NET AJAX controls are created during the Sys.Application.Init event. If you try to access them earlier (e.g. in the window.onload) the $find() will not work.

how to pass session value from code behind to javascript

i have made a session variable Session["Background1"] = value; in one of my code behind function i want to retrieve this value in my javascript function.
ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "SessionValue", "var sessionValue = '" + Session["Background1"] + "';", true);
Personally, I prefer to do it the scripting way. Suppose your variable is currently declared in your Javascript as:
var background1 = null; // TODO: Add value from session.
To add the value from session, all you need to do is this:
var background1 = '<%= Session["Background1"] %>';
When the page is output by ASP.NET, the expression between <%= and %> is evaluated and written to the page, effectively becoming a Response.Write. As long as the member is available in your page at the public or protected level, you can push it into your Javascript it in this way.
I find this approach easier to work with than the obnoxiously verbose ClientScriptManager.

Categories

Resources