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

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*/");

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

MVC C# Code in Javascript

On a cshtml page in my View i easily get the URL to an action with thise line:
<h1>#Url.Action("NewComment", "Case")</h1>
And if I write this in Javascript:
<script>
alert('#Url.Action("NewComment", "Case")');
</script>
It also comes up correct in the alert.
However my problem is that at the bottom of the page I have several other javascript beeing referenced like this:
<script src="~/Scripts/custom/SomeScript.js"></script>
And if I write alert('#Url.Action("NewComment", "Case")');
In that file. It just comes up as #Url.Action("NewComment", "Case") in the alert box.
So how come it doesn't work in this file?
In the same file I also have a click method with $.ajax({ method and the url is referenced like this: url: '#Url.Action("NewComment","Case")', and here it works fine again.
So how come it works here again? Is it something with that Ajax method is a Jquery Object??
The spesific problem I have is that I need to reference the URL.Action method i the Ajax call of a Jquery Datatable.
var table_comment= $('#comment_table').dataTable({
"sDom": "<'dt-toolbar'>",
ajax: {
url: "/Case/NewComment/", //This works but want to change it to use URL Action
url: '#Url.Action("NewComment", "Case")', //don't understand why this doesn't work
type: "POST",
data: {"id": Case_ID }
},
The reason that #Url.Action("NewComment", "Case") works in *.cshtml, is that it is rendered to HTML on the server by ASP.NET MVC. As for your *.js files, these are not transformed by ASP.NET MVC, so what you see is what you get.
Specifically, .cshtml files are C# Razor templates, which get rendered by ASP.NET MVC to .html files.
As for your .js files, perhaps you could work around this by defining your URLs as global variables in your .cshtml, which you simply refer to in your .js files.
<script>
var newCommentUrl = '#Url.Action("NewComment", "Case")';
</script>
You cannot write Razor syntax inside separate js file because after all its Razor syntax '#' which only
Razor engine could interpret(and could be written inside .cshtml extension Pages only) and razor engine
convert it to appropriate HTML so that is why
in separate js file file when you write alert("#Url.Action("NewComment", "Case")") it comes as
#Url.Action("NewComment", "Case")
You can't have razor syntax ( #Url.Action ) inside a linked JavaScript file - Visual Studio doesn't work like that.
As a solution, write out your variables in javaScript in your CSHTML file like so:
<script type="Text/javascript">
var dataTableURL = '#Url.Action("NewComment","Case")';
</script>
And then underneath this reference your external javascript file
<script src='#Url.Content("~/Scripts/MyJavaScriptFile.cs")' type="text/javascript"></script>
And modify your javscript variable to use the above variable:
var table_comment= $('#comment_table').dataTable({
"sDom": "<'dt-toolbar'>",
ajax: {
url:dataTableURL,
type: "POST",
data: {"id": Case_ID }
},
I found out a way better solution for this!
RazorJS :) Works perfect.
http://www.nuget.org/packages/RazorJS

Call C# function from Javascript in aspx webform and then reload page

Trying to figure out how to call a c# function in a webform. I tried both ajax and windows.location but could just be off on my path. Trying to send it my c# code at SpeakerList.aspx/update and then gonna attach two variables i have in javascript which shouldnt be too bad. But want it to hit the C# function then reload the page so hoping there is just an easy call im missing.
buttons: {
"Save": function () {
var combo = ASPxClientControl.GetControlCollection().GetByName('DropDownList1');
var value = combo.GetSelectedItem().value;
var billID = $("#billID").val();
window.location = "SpeakerList.aspx/updateRec";
}
You might want to try using WebMethods:
http://aspalliance.com/1922_PageMethods_In_ASPNET_AJAX.all
This allows you to call a function in your page's code behind using JavaScript.
Assuming you are using MVC, you probably want to return a JSON result. An easy way to consume Json within your client webpage is using JQuery. You can return JSON as as the output of a webpage, but I don't recommend it. Create a separate service point that repesents the JSON method.
It is hard to tell what you are actually trying to accomplish, but the normal usage pattern for a JSON method is the supply the parameters as part of the querystring (which you can refactor with routing if you want). The result is then just a JSON packet.
Personally, I like JSON.Net for server side JSON, but you don't actually need this. Look up JSONMethod for examples, etc. that will show you how to do this.
From the browser client, JQuery has a json method, but I personally recommend using the more generic ajax method a JQuery so you can use the handlers for success, error and completion. E.g.
$.ajax({
url: "http:...",
data: queryparm,
cache:false,
timeout:15000,
success: function(data){
jresult = $.parseJSON(data);
...
},
error:function (xhr, ajaxOptions, thrownError)
{
setErrorMsg("Error getting search results: " + thrownError);
}
});
EDIT -- Actually, I've done this exact same thing with webforms too, code is essentially identically (if you use JSON.Net on the server side). You don't have the routing options to make the urls REST compliant, but as an internal json web service, you probably won't really care about that.
As a webpage (.aspx) page, you can use a "postback" this is the simplest method for a web form. You can always declare some hidden fields to use for data passing if you are not passing back a native "control" value. If you don't know how to do this, you need to read a tutorial on using web forms.

Call javascript with C# from WebService (.NET)

I have a web page with JavaScript that calls C# methods using jQuery and AJAX. This works fine. I would like to know how to call JavaScript functions from the C# code, if this is even possible. If it's not possible, is there a sane alternative?
Assuming the browser initiates the interaction
In general, your server-side C# code will respond to interactions initiated by your client-side code. If you're looking for ways your C# code can initiate the interaction in the absense of a browser request, see the next section below.
If you're processing a full page response, then of course you can just output script tags containing the call you want to have occur. Make sure that the script is making the call after the function it's calling has already been defined by an earlier script tag, and if there's going to be DOM interaction be sure to put that script at the bottom of the page (or use jQuery's ready feature).
Responding to Ajax calls, it's possible for the C# code to return strings containing JavaScript code, which your in-page code would then execute (e.g., via eval or similar), but it's generally best to avoid that.
Instead, have the C# code return data in response to an Ajax call, and have your in-page code respond to that data by calling the appropriate function.
A bit of a hybrid of the two is to have your C# code return data that indicates what function to call and what arguments to supply to it, and to have a map of your functions that you index into with the function name, e.g.:
var functions = {
foo: function(arg0, arg1) {
alert("foo called with " + arg0 + "," + arg1);
},
bar: function(arg) {
alert("bar called with " + arg);
}
};
$.ajax({
url: "/path/to/resource",
dataType: "json",
success: function(data) {
if (data && data.fname && data.args) {
functions[data.fname].apply(undefined, data.args);
}
}
});
There, your C# code would return a string containing information encoded in JSON as an object with an fname property (a string giving a function name) and an args property (an array of arguments to pass to the function), which jQuery will deserialize into an object for you. Then we look up the function object in the map using its name (functions[data.fname]) and use the built-in Function#apply to call it and pass in the arguments. That works because you can refer to JavaScript object properties using either dotted syntax and a literal for the property name (obj.propName = 42), or using bracketed syntax and a string for the property name (obj["propName"] = 42), where in the latter example the string can be any expression, including a variable or property reference (name = "propName"; obj[name] = 42;) — which is how we're looking the functions up on the functions map.
I'm not suggesting you do that, just saying it's possible.
If you're trying to have the server initiate the interaction
If you want the server to reach out to the browser instead, you'll have to have some channel of communication established between them, either using the new (and variously supported) web sockets API, or various Comet techniques.
Javascript function can not called directly from C#, rather Javascript function/code block can register with page from C# code behind which is called after render or called when it is necessary.
//Register Script block for JS code
Page.ClientScript.RegisterClientScriptBlock(GetType(), "ScriptBlockKey",
"<script> alert('JS alert written in C# code behind.');</script>", false);
//Register Script block for calling JS function
Page.ClientScript.RegisterClientScriptBlock(GetType(), "ScriptBlockKey",
"SomeJSFunction();</script>", false);

PageMethods in ASP.NET failed to work if you have ASP.NET Routing Implemented

I have a web method:
[System.Web.Services.WebMethod]
public static string getCharacterstics(int product_id, int lang_id)
{
// code goes here...
}
I want to access it using PageMethods like:
(Provided the condition that i have Enable PageMethods in ScriptManager):
<script type="text/javascript">
$(document).ready(
function () {
$('#characterstics').html("loading");
// '<%= product_id_property %>' , '<%= this.LanguageID %>'
PageMethods.getCharacterstics(0 ,0 , OnSave);
}
);
function OnSave(result) {
}
</script>
I get the error "the http verb post to access path.. is not allowed"
I googled it and search the SO too but does not get any solution regarding to it Based on ASP.NET Routing.
What i believe is that because of asp.net routing the service methods are not accessible.
In addition i think i cannot even use JSON because of asp.net routing too.
Any help is appreciated.
Updated:
If i run the page with this url:
http://localhost:2606/searchdetail.aspx
The web method executed successfully.
Now
I have routing like this:
routes.MapPageRoute("searchdetail", "searchdetail/{ID}", "~/searchdetail.aspx");
routes.MapPageRoute("searchdetail", "searchdetail", "~/searchdetail.aspx");
The set_path() will work only for case 2 i.e without ID but does not work with case 1
if i try
http://localhost:2606/searchdetail
It works fine
but if i try to use:
http://localhost:2606/searchdetail/123
It gives error that object expected.
So set_path() is the option what should i write.
Currently, WebMethods don't work transparently with the Routing framework. There is a work around. You have to access the PageMethods directly by doing the following in your javascript:
PageMethods.set_path('/the/path/to/your/page.aspx');
PageMethods.YourMethod(params, onSuccess, onFailure);
I hope this helps.
I kept running into this myself. With routing enabled, if I added a value to the path, it would start to fail again. This solution is a bit of a hack, but it seems to be working consistently.
Create a server control hyperlink where the navigate url refers to itself, then once the control renders, grab the href and use it for set_path
This gets around the issue of set_path not referring to the correct location if you called
<asp:HyperLink ID="hlPage" runat="server" NavigateUrl="~/user.aspx" ClientIDMode="Static"></asp:HyperLink>
<script>
$(document).ready(function () {PageMethods.set_path($('#hlPage').attr('href'));})
</script>

Categories