Load .NET Resources Client-Side on each request - c#

I have the following JavaScript snippet:
<script type="text/javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_beginRequest(ajaxBeginRequest);
prm.add_endRequest(ajaxEndRequest);
function ajaxBeginRequest(sender, args) {
$.blockUI({ message: '<h1><img src="/images/ajax_loading.gif" /> <%= MyNameSpace.SomeWhereElse.Shared.RandomLoadingMessage() %></h1>' });
}
function ajaxEndRequest(sender, args) {
$.unblockUI();
}
</script>
Right now the C# line runs at page load and gives me one random message, but it is constant through the page execution until the page is refreshed. What I'd like it to do is give me a different message on each ajax Request
Any suggestions for this?

You can make a ajax call to a web service (called script service) to get the message on each invocation. See this article where it explains how to call script services using ASP.NET generated proxies as well as using jquery methods. You can use either method.

Related

How do I inject javascript code via webview?

Basically what I want to do is this this but I can't seem to find something similar for webview XAML control. What I ultimately need to do, is capture an incoming json file from the webview. As is, I get a bad request from the server and unsupported file exception from the webview. I thought about injecting a javascript so that it would alert me, I could get the body of the incoming json and bypass all the errors.
There are two main things you can do:
Call functions programically
Inject any code by using the HTML string
Function Calling
You can use InvokeScript to call javascript functions.
If you have in a webpage with a script:
<script lang="en-us" type="text/javascript">
function myFunction() {
alert("I am an alert box!");
}
</script>
Then you can in C# call:
MyWebview.InvokeScript("myFunction", null);
Which will execute the script function myFunction.
Injecting Text
If you download the HTML page and all other needed files(using the Windows HttpClient), you can inject any code by manipulating and then Navigating to string.
Lets say you want to change the above script to add another function, "HelloWorld", then you can
Search the file for something you know will be there, such as: <script lang=\"en-us\" type=\"text/javascript\">
Using string manipulation, add the desired text, such as a function (but this can be anything)
Navigate to the String
The C# code:
string MyWebPageString = GetWebpageString(WebpageUri);
string ScriptTagString = "<script lang=\"en-us\" type=\"text/javascript\">";
int IndexOfScriptTag = MyWebPageString.IndexOf(ScriptTagString);
int LengthOfScriptTag = ScriptTagString.Length;
string InsertionScriptString = "function SayHelloWorld() { window.external.notify(\"Hello World!\");} ";
MyWebPageString = MyWebPageString.Insert(IndexOfScriptTag + LengthOfScriptTag + 1, InsertionScriptString);
MyWebview.NavigateToString(MyWebPageString);
The result will be that the navigated to Webpage will look like this:
<script lang="en-us" type="text/javascript"> function SayHelloWorld() { window.external.notify("Hello World!");}
function myFunction() {
alert("I am an alert box!");
}
</script>
Since the injection can be applied to any area, even the HTML, you should be able to figure something out.
Hope this helps. Good luck.
This answer was based on this MSDN blog

Create new Script within <div> from C# and Reload newly created Script

I would like to implement the following, which would appear to be fairly easy, but I have been searching for a working example without success.
i) I have an HTML Tag in an aspx Page with an identification:
<div id="demo" runat="server">
ii) This Tag contains the following Script Tag, which itself has an identification:
<script id="scriptdemo" type="text/javascript" src="http://www.myurl.com/myquery"></script>
iii) I have an AJAX call which calls a Server Function (which is working without any issue)
iv) From that Server Function, I would like to either modify the “src” Attribute of the Script, or create and insert a new script in the existing division with a new src if this solution is easier to implement.
v) After executing the Server Code contained within the Server Function, the flow is properly passed back to the client (here again, I do not have any issue with this process).
vi) Once back on the client, I would like to refresh/reload the newly created script (or updated src attribute) using JavaScript/AJAX (either standard Javascript or JQuery).
Would someone have a working example of such code?
Check out http://api.jquery.com/jQuery.getScript/
It's basically shorthand for $.ajax with datatype as "script". This will load a script file for you, and give you the chance to run a callback when it's done.
$.ajax({
url: "your/ServerMethodThatReturnsScript",
dataType: "script",
success: successCallback
});
becomes
$.getScript("your/ServeRMethodThatreturnsScript", function() { /* some success callback */ });
In the event you can't do this but CAN make an ajax call to your server, you can use the eval method to execute any string that is in the form of javascript:
eval("/*some javascript*/");

Timer with javascript and C#

I need to create a timer in an ASP.NET web page.
I have tested some JavaScript code like:
window.onload = function WindowLoad(event) {
setTimeout(function () { alert("DoIT") }, 60000);
}
and it works like expected but when I replace the alert with a call to a C# function like:
window.onload = function WindowLoad(event) {
setTimeout(function () { <% doIt(); %> }, 60000);
}
the function works on the load of the page and not after the specified period.
<% doIt() %> runs during the server side process, not on client. If you want to do something on the server side you should create a webmethod and make a post to it.
Try this blog post, this should be what you are looking for: http://deebujacob.blogspot.com/2012/01/aspnet-ajax-web-method-call-using.html
It's like other people sad you can not call server side functions directly from javascript you have to make a request, that's is way good God gave as ajax :)

How to execute javascript in specifci time in .cs?

If i have script like this :
<script type="text/javascript" src="//www.gmodules.com/ig/ifr?url=http://hosting.gmodules.com/ig/gadgets/file/100080069921643878012/facebook.xml&up_useNewFB_p=1&up_showPopUp2_p=true&synd=open&w=320&h=500&title=Facebook&border=%23ffffff%7C3px%2C1px+solid+%23999999&output=js"></script>
and i wanna to execute this script in specific time in my .cs code how to do this?
string rowTestHide = #"<script type="text/javascript" src="//www.gmodules.com/ig/ifr?url=http://hosting.gmodules.com/ig/gadgets/file/100080069921643878012/facebook.xml&up_useNewFB_p=1&up_showPopUp2_p=true&synd=open&w=320&h=500&title=Facebook&
border=%23ffffff%7C3px%2C1px+solid+%23999999&output=js"></script>";
ClientScript.RegisterStartupScript(this.GetType(),"rowTest", rowTestHide);
Try out with following code,
Page.ClientScript.RegisterClientScriptInclude("MyScript", "<script type="text/javascript" src="//www.gmodules.com/ig/ifr?url=http://hosting.gmodules.com/ig/gadgets/file/100080069921643878012/facebook.xml&up_useNewFB_p=1&up_showPopUp2_p=true&synd=open&w=320&h=500&title=Facebook&border=%23ffffff%7C3px%2C1px+solid+%23999999&output=js"></script>");
The only real way to do this at the moment (without using something like SignalR) is to implement a polling system.
You will have to have an Ajax call, that makes a request to your server every xxx seconds, using something like:
window.setTimeout(function(){ /* do ajax request */ }, 5000);
Which would run every 5 seconds.
If the desired result comes back from the DB, you'll have to then programatically inject the required script block into your page.
take a look at this:
jQuery AJAX polling for JSON response, handling based on AJAX result or JSON content

jQuery "Microsoft JScript runtime error: Object expected"

I have the below code that does not seem to work at all :( I keep getting:
Microsoft JScript runtime error: Object expected
The error seems to occur when the timeout is done. So if I raise the timeout with 10 seconds the error holds for another 10 seconds.
I want to be able to update the number of friends online async. The number is shown with the following html:
(?)</strong>
The friends part is set at the first run, but when the timeout calls back it does not fire again. Also, I cannot see on which line the error occurs because if I want to break on the error it just shows "no source code" etc.
The code below is the code I'm using. Thanks!
<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.3.2.js" type="text/javascript"></script>
<script src='/Scripts/MicrosoftAjax.js' type="text/javascript"></script>
<script src='/Scripts/MicrosoftMvcAjax.js' type="text/javascript"></script>
<script src='/Scripts/jquery.autocomplete.js' type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
UpdateFriendsOnline();
function UpdateFriendsOnline() {
window.setTimeout("UpdateFriendsOnline()", 1000);
$.get("/Account/GetFriendsOnline", function(data) {
$("#friendsOnline").html("(" + data + ")");
});
}
});
</script>
Change your setTimeout() like this:
window.setTimeout(UpdateFriendsOnline, 1000);
Currently your function isn't available outside the document.ready, so it's not accessible as a global function, which passing it as a string is trying to access it as. As a general rule, never ever pass setTimeout() a string if you can avoid it...it can cause problems like this case, and I can't think of an example (that if avoidable) is made better by it being a string.
Also, I suggest firing it when you get the response back, otherwise you'll start queuing up overlapping ajax requests, you can do that by adjusting your function to this:
function UpdateFriendsOnline() {
$.get("/Account/GetFriendsOnline", function(data) {
$("#friendsOnline").html("(" + data + ")");
window.setTimeout(UpdateFriendsOnline, 1000);
});
}
Try this:
window.setTimeout(UpdateFriendsOnline, 1000);
The version you had would have worked if the function was defined in the global namespace.
This way, you're passing in a local reference to the function, which will get called every second.
EDIT:
If you need to cancel the previous request before the new one starts, you can do something like this:
<script type="text/javascript">
$(document).ready(function() {
var request; // Stores XMLHTTPRequest object
UpdateFriendsOnline();
function UpdateFriendsOnline() {
if(request) request.abort(); // Abort current request if there is one
window.setTimeout(UpdateFriendsOnline, 1000);
// Store new XMLHTTPRequest object
request = $.get("/Account/GetFriendsOnline", function(data) {
request = null; // Clear request object upon success
$("#friendsOnline").html("(" + data + ")");
});
}
});
</script>

Categories