Calling JavaScript function from server-side? - c#

So this seems famous, but with little different.
JavaScript Function:
function ShowMessage(Message, Title, isAlarm) {
$("#dtext").html(Message);
$("span.ui-dialog-title").text(Title);
$("#dialog").dialog({
open: function(e) {
var Dia = $(e.target);
if (isAlarm == true) {
Dia.parents(".ui-dialog:first").find(".ui-dialog-titlebar").css("background", "red");
Dia.parents(".ui-dialog:first").find(".ui-dialog-titlebar").css("color", "White");
}
else {
Dia.parents(".ui-dialog:first").find(".ui-dialog-titlebar").css("background", "LightSeaGreen");
Dia.parents(".ui-dialog:first").find(".ui-dialog-titlebar").css("color", "White");
}
},
show: "blind",
hide: "clip",
modal: true,
resizable: false,
buttons: {
"Close": function(e) {
$(this).dialog("close");
return true;
}
}
});
}
As you see this method fill with Jquery-Code. if this is just java-script, We can use this Code to call that function but in this case this method don't work well.
C# calling JS Method:
if (!Pointer.ClientScript.IsStartupScriptRegistered("message"))
Pointer.Page.ClientScript.RegisterStartupScript
(Pointer.Master.GetType(), "message", "ShowMessage('messageBox','" + Message + "',false);", true);
I don't Know how to resolve this problem. I Want just call this Js function from server-side?
Edit 1
Thank for your attention. some guy's want from me describe my problem better. Why I can't ?
Cuz I don't know what's exactly problem.
I just can say, I test this program with FireBug and set break-point on first line on JS function but in run time when I call that Js function that break-point Hit for a few Millisecond and then page reload goes complete and nothing happened.
I'm newbie on JS and jQuery. So Instead hitting down vote plz try sample program with these Code's and help Me.
thank Again (specially Stefan, PirateKitten, Widor)
Edit 2
I made this Function(JQuery Message Function) to replace Old Function which only use simple JS alert. and I must say old version work(even if I call that from server-side with JS-Caller-Function I write).
in this case, even if I call new Function(JQ Function) with Js in page like :
<button type="button" onclick="ShowMessage('hi','title',false)">
Display Message
</button>
It's worked, But when call that from server side, Function don't work.

Put simply; you can't.
JavaScript runs clientside, C# runs serverside.
However, you can generate JavaScript serverside and output it to the client.
See my answer here: Call javascript from vb.net code behind

Code that is registered with Page.ClientScript.RegisterStartupScript is "rendered" at the end of the page. To be exact in a script tag before the form close tag. However, the code might run before the DOM tree is fully generated.
Since your ShowMessage function access the DOM tree your issue could be related to missing DOM tree elements.
If I do interpret your question correctly there are no JS erros on the page. This chould be as a result of the jquery selector behavior:
$("#dtext").html(Message);
This will set the HTML of all elements with the id dtext. Since there might be no elements with the ID dtext yet, $("#dtext") will return an empty collection and no actions are taken.
To workaround this issue you can try to run your code in the the jquery document ready event. jQuery fires this event if the page was fully loaded:
$(document).ready(function() { ShowMessage('messageBox','" + Message + "', false); }
ServerCode:
if (!Pointer.ClientScript.IsStartupScriptRegistered("message"))
Pointer.Page.ClientScript.RegisterStartupScript
(Pointer.Master.GetType(), "message", "$(document).ready(function() {ShowMessage('messageBox','" + Message + "',false); }", true);

you can call js function from server side like this
Page.ClientScript.RegisterStartupScript(this.GetType(), "show", "ShowMessage()",true);
Hope this would help you

Related

How to make javascript interact with .aspx page?

I wish to run some asp.net code on a page generated by Wordpress. Is there a way using XMLHttpRequest() to make JavaScript interact with .aspx page just like a Servlet?
For example, I hope that I can do this in JavaScript:
xmlHttpRequest.open("POST", "http ://some.aspx", true);
send_request("request=add,1,2");
function getReadyStateHandler(xmlHttpRequest) {
//handle_response
}
How to write and configure such an asp page? Does someone know a good tutorial?
Thanks a lot!
You are better of using JQuery for this task.
It is Javascipt library that has exactly functionality that you re looking for
You can call your backend methods to invoke serverside action that would return JSON object. and then in done function process the result.
$.ajax({
url: "test.html",
context: document.body
}).done(function(result) {
var dataFromTheSreverside = result;
$( this ).addClass( "done" );
});
Here you can find a lot of examples

Getting a downloadable file with an ajax request

Edit: Not sure why this was marked as a duplicate given that the original doesn't even really have an answer other than "use this third party tool that adds extra interface stuff that you probably don't want or need". The reason I was using ajax is because I need to send an array of ids and I'm not sure how to do it other than with ajax. I figured out what I need to do, so I don't really need any more help from this post, but this definitely isn't a duplicate question, and even if it were, there isn't a real answer to the original.
I've been trying to get a link that will download a file generated by my export script. However, I can't get it to get the returned file. This is the JS function I've been using...
function sendSelected(path) {
var ids;
ids = jQuery("#grid").jqGrid('getGridParam', 'selarrrow');
if (ids.length > 0) {
alert("");
$.ajax({
url: path,
data: { ids: ids },
type: "POST",
traditional: true,
});
} else {
alert("You have not selected any rows.");
return false;
}
}
and then here's the HTML portion...
<input type="submit" name="command" value="Export" />
<script type="text/javascript">
jQuery("#export").click(function () { sendSelected("/Forms/Export"); });
</script>
This all works fine, except my exporter ends with document.Save(response, "file.pdf"); and the page isn't getting this back. If I change it to document.Save(response, #"C:\some\location\to\save\at.pdf"); the file is created there, so I know it's not a problem creating the file. Also, if I just create a standard form that points to /Forms/Export and then manually enter the ids, I can download the file fine, but that doesn't work for my implementation.
$.ajax will not work, i was attempting something similar recently but ended up with different solution. Simply have a form with hidden input and then in your sendSelected set the field and action and then submit form.
$("#hiddenField").val(data);
$("#yourForm").attr("action", path)
$("#yourForm").submit();

Using Server side method from Javascript without AJAX

I have a tricky problem. I am in a situation where I need to use a method defined in a .cs file from a javascript function. The problem is we are using .NET 1.1 and AJAX cannot be used for the application.
Also, I will need to pass a string from the javascript to the server side method. The page where I am implementing the javascript is a .as Any ideas?
I have tried doing a post back and creating a RaisePostBack event handler method (both in the .aspx page and the .ascx user control) but no luck.
It will be greatly appreciated if someone could help me out with the problem.
To be more precise. I have a class Attachment.cs which has a method Delete().
The javascript is called from a span's onclick event. The javascript function's input parameter would be a string which I will need to use to instantiate an Attachment.
I created a method which instantiates an Attachment using a string and calls the corresponding Delete() method for the Attachment object.
Now, I will need to pass the string from javascript function to the method I have created. I cannot use PageMethods.
The Javascript function is like:
// File ID is a string
function DeleteAtt(fileID)
{
//I tried PageMethods here, tried posting the page and getting the value through
// a RaisePostBack event etc. No luck.
}
The cs method I created is like:
public void DeleteAttachment(string ID)
{
Attachment obj = new Attachment(ID);
obj.Delete();
}
Do you mean that Microsoft's "ASP AJAX" is not an option, or do you mean that any jquery/any other library, or your own hand written javascript ajax won't work? ASP AJAX may not be supported by you version of .net, but surely simple javascript will still work, as you want to access the page from javascript.
If this is the case, something as simple as this, using jquery, would work:
function submit() {
$.post(
"pagename.aspx?string=" + variable,
function (data) {
alert("Response: " + data);
});
}
How about adding a callback-url as a query string to the url that you need to submit data to? Example:
Initial Page:(javascript)
function send(){
window.location = "submiturl.aspx?str=var&
callbackurl=http://www.myurl.com/page.aspx";
}
submiturl.aspx then catches both query strings [str] and [callbackurl], performs the action/function and then sends a response back to the [callbackurl]
response.redirect(callbackurl + "?response=" + data);
Initial Page now uses response.querystring to determine if it was succesful/whatever else you want and continues its business.
This definitely does not use ajax, and would be, by no means, asynchronous, but is based on a pretty lengthy history of API/callback & response design.
You can inject an invisible Iframe into the page and the SRC of the iframe can be used to pass data back to the server.
This is a very old technique back before jQuery and Prototype were invented.
See: http://www.ashleyit.com/rs/ for other alternatives.

Calling a javascript function from Page_Load in code-behind

How can I call a javascript function, that is in the aspx page, from the Page_Load method, in the code-behind?
The simple answer is, you can't. The code in the Page_Load method executes on the server, javascript executes on the client.
If what you want to do is add a call to a javascript method, in the Page_Load so that once the page is loaded by the browser, the javascript executes, then you can use the ScriptManager:
if (myConditionForAddingCallToJavascriptIsMet)
{
Page.ClientScript.RegisterClientScriptBlock(typeof(ScriptManager), "CallMyMethod", "myMethod();");
}
else
{
// Do something else, add a different block of javascript, or do nothing!
}
To use this, you'll need to have an <asp:ScriptManager> element in your markup for it to use (if memory serves, an exception will be thrown if you don't have one). The text "CallMyMethod" is used by the ScriptManager to uniquely identify the script that it injects for you, and the text "myMethod();" is embedded, so you'll end up with an additional script element in your page similar to this:
<script language="javascript" type="text/javascript">
myMethod();
</script>
The easiest way is to use the page's ClientScript property. You can register some code to run when the page loads using something like
ClientScript.RegisterStartupScript(GetType(), "hiya", "alert('hi!')", true);
See http://msdn.microsoft.com/en-us/library/asz8zsxy.aspx for more info.
This should be available from a child control by tacking "Page." onto the beginning of the code above.
Why would you want to do this?
What's the purpose?
Anyway you can do the following, but I DON'T recommend it!!! :
protected void Page_Load(object sender, EventArgs e)
{
string pagename = "Test.aspx";
String scriptString = "<script language=JavaScript> function DoClick() {";
scriptString += " window.showModalDialog('" + pagename + "' )}";
scriptString += "</script>";
if(!this.IsStartupScriptRegistered("Startup")) //This is **not** a good practice
this.RegisterStartupScript("Startup", scriptString);
}
Can you supply with more information of what you want to achieve to get better answer..
Shide's solution works. The problem is if you want to run your piece of code only on postback, for example. The solution I found was to use a "cookie": I verify if cookie x exists, if it doesn't I run the javascript code and set the cookie. When you hit refresh, the cookie will be found so the piece of code won't run.
function pageLoad() {
if(localStorage.getItem("cookie") === null) {
localStorage.setItem("cookie", true);
//run code
}
}
Any code you need to run every single time just leave it out of the if statement.
You need to use Register client Script:
MSDN
CodeProject
I do it in a Page Load method:
if (!this.ClientScript.IsClientScriptBlockRegistered(this.GetType(), "HelpScript"))
{
var scriptSource = "function ShowHelp() { alert(""); };\n";
ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "HelpScript", scriptSource, true);
}
but I don't think it's recommended
I mean... you can do this, and it'll work. But for me the only good reason of inserting a script from asp.net page is to get some client side features of server controls.
So for example to get an instance of control:
var myControlId = this.control.ClientID;
But writing entire javascript functions and logic on the server side is not comfortable when you need to change it or debug it (for me it's hardcoded string).
If you just want to call a JavaScript function ( and do not need to pass something from code-behind, then use this...)
document.onload = function () { your-function(); };
window.onload = function () { your-function(); };
document.readyState = function () { your-function(); }
... depending on your specific requirements.
Hope this makes sense to you & answers your question.
this is a little trick i found myself without having server side code .
that function will be called when the page loads (can be used with an update panel) :
<script>
function pageLoad() {
//Do your stuff
}
</script>
it is unknown and yet works like a charm
Please try this code:
ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "MyFun1", "test();", true);

How access Jquery TreeView on the server?

How do I access Jquery Treeview inside the .aspx file upon form submit?
also, Can I add nodes to Jquery Treeview on the fly? (on the client side)
I am using asp.net web forms, c#
EDITED:
someone mentioned the following in one of the questions:
"on form submit, someone is going to have to write code on the client to collect that data and send it via Ajax to a server method"
how is this done?????
Well, I think I've found what you want. Take a look here.
In brief, you must define a WebMethod on your server side, and then you can easily access it using jQuery. An exellent working example is under the link above, and here I'll modify it to show how you can pass arguments. So...
In your page code-behind *.cs:
// We'll use this class to communicate
public class Dog
{
public string Name { get; set; }
public string Color { get; set; }
}
// This is your page, in my case Default.aspx
public partial class _Default : System.Web.UI.Page
{
[WebMethod]
public static string ProcessData(Dog myDog)
{
return "Your " + myDog.Color + " dog's name is " + myDog.Name + "!";
}
}
Then on your *.aspx:
<script src="jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="json2.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#btnProcess").click(function() {
// This is what we want to send to the server
var dogItem =
{
Color: $("#txtColor").val(),
Name: $("#txtName").val()
};
// And this is how it should be sent - in serialized way
var dogItemSerialized = JSON.stringify(dogItem);
$.ajax({
type: "POST",
url: "Default.aspx/ProcessData",
data: "{'myDog':" + dogItemSerialized + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#result").text(msg.d);
}
});
});
});
</script>
Color: <input id="txtColor" type="text" /><br />
Name: <input id="txtName" type="text" /><br />
<input id="btnProcess" type="button" value="Click Me" />
<div id="result"></div>
So here you fill textboxes and then your data is sent to the server which understands it as a Dog object. Pay attention to arguments passing, because this is the most confusing part. You should pass them in JSON format, which is a little bit "too-much-stringy". So I use here json2.js script which helps to convert usual javascript object into JSON-serialized string (JSON.stringify() method). It is available here. But it is still rather ugly =) It is important that I pass argument called "myDog" which value is the serialized dogItem. Because this is exactly what the server expects to get (so, for example, I can't change the argument name, this won't work:
data: "{'someAnotherArgumentName':" + dogItemSerialized + "}"
And the last thing. Pay attention to the following line:
success: function(msg) {
$("#result").text(msg.d);
}
If you are working with ASP.NET prior to 3.5 (for example, ASP.NET 2.0), then you'll need to write just $("#result").text(msg) instead of msg.d. Only ASP.NET 3.5 encapsulates all the data under "d" member for some reason...
Anyway, in the above article you can find useful links (both inside the article and in comments), so you can read more about arguments, "msg.d" and so on.
I hope this helps!
Since jQuery Treeview is a client-side component, you can't access it from the server-side. So in order to pass any data from your tree to the server, you have to write client-side javascript code (actually jQuery code). The same thing regarding adding nodes to the treeview on the fly: only using client-side jQuery code. Remember that your C# on the server-side has no idea about your TreeView.
The integration between jQuery and ASP.NET WebForms is rather problematic and "not so natural", because ASP.NET is built on different concept... So if you are working with ASP.NET WebForms, I would suggest you to use server-side components instead (it can be Microsoft's own ASP:TreeView or other 3rd-party WebForms-aimed components). Alternatively, you can try the new ASP.NET MVC Framework - it is built on more common (for other web-development platforms) concept, and the integration between it and jQuery is straightforward (actually jQuery is even shipped with it).
Don't get me wrong... I am not saying that the integration between jQuery and ASP.NET WebForms is totally impossible. It is possible. But you'll need to do "not-so-beautiful" things and work hard for every simple operation. If you still want to use jQuery, then use it only for the client-side animations...
UPDATE: As for this quote - "on form submit, someone is going to have to write code on the client to collect that data and send it via Ajax to a server method" - well, this is exactly what I am talking about. On the client-side you call javascript method when submitting the form (for example, by setting onclick='mymethod();' on your "Submit" button). This code does what it needs to do and then... it is supposed to perform AJAX call using jQuery nice syntax. But this won't work with ASP.NET WebForms, as I've explained before. Well, you can read about Microsoft AJAX Client-side library (here: http://msdn.microsoft.com/en-us/magazine/cc163300.aspx), perhaps this will help. But I still think that this integration won't be easy and straightforward. Use jQuery for the animation and ASP.NET server-side components for all other things!

Categories

Resources