Using Server side method from Javascript without AJAX - c#

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.

Related

Get reference to instance of the calling aspx from ashx in ASP.NET WebForm

I'm in the code behind of a generic http handler (.ashx) and I'd like to get a reference to the instance of the calling .aspx page, so I can call some methods/get some properties of it. I can easily call static methods of the page, but I'm not able to get the actual object instance.
Is there a way, without resorting to services/webmethods/whatnot? Thanks!
EDIT:
I call the ashx from the JS inside the aspx page
$.ajax({
url: "handler.ashx",
context: "my content"
}).done(function() {
alert("Done");
});
Then I update an asp:Label with the result of it.
I've found a way to do it anyway (you can do it via JQuery from JS for instance), but now I'm curious if you can do it from the code behind simply calling some pageInstance.setMyLabel(ashxResult) or something like this.
There is no direct way to modify the contents of your calling .aspx-page via server-side code.
You should (like you mention yourself) process the results of the call to your .ashx-handler with javascript.
If you would like to use some results 'serverside' I think the only option is that you write some data to the session-object during the processing of the .ashx-handler.
On the next postback of the .aspx-page you could use that data to accomplish some change. If you would like to do that, please refer to this question also:
How to access Session in .ashx file?
The instance of the page class only exists for as long as it takes to process the request and send the response back to the client. By the time the Javascript code executes and makes a request to the ashx file, the page instance has been destroyed.
ASP.NET Page Life Cycle Overview | Microsoft Docs

passing javascript parameters and using them in unity C# files

I want to pass some javascript parameters at runtime (webplayer) to unity and using them in my network.cs script.
<html>
<script type="text/JavaScript">
//<![CDATA[
PlayerName = "Adam";
playerID = "56";
//]]>
</script>
</html>
Just consider I am using the above parameters to log in users.
You need to send the data from the webpage to the Unity3d container. You can do something like this:
u.getUnity().SendMessage(GameObjectName,MethodName,stringParam);
where:
u is the Unity3d container object created by unity if you use their template.
GameObjectName is the name of a game object that you placed somewhere on the stage
MethodName is the name of a method that's available for that GameObject, that means that it will be a method defined in one of the components (MonoBehaviour) that you attached the the GameObject
stringParam si the parameter that you pass to MethodName, the method can only accept one string param, so you need to serialize your data, you can use JSON.parse( {"playerName":PlayerName,"playerId":playerID} )
On the C#/Unity side you need to implement a MonoBheviour that has a
void MethodName(string param);
defined that reads the string and with a JSON parser gets the data out.
You would need to post that data back to your server. Using AJAX is probably want you want if you don't want your whole page to reload.
A commonly used framework, facilitating ajax is jQuery.
You would need an endpoint, writting in your c# (guessing from your fileending on network.cs) to read what your clientside javascript is posting. I don't know what version of .net you are on, but look into WebAPI - it is very easy to implement.
TL;DR
Use javascript/jquery to post your data from the client to the server.
Read the posted data on your serverside, though either WebAPI or just a normal .aspx page reading querystring/form values
If you just want to send data from the client, and not worry about any response, you can use
$.ajax({
type: "POST",
url: url,
data: {PlayerName: PlayerName, PlayerId: playerID},
});
You can change POST to GET if you want the make a get request instead. The data will be readable through Request.Form or Request.QueryString if you use a normal .aspx page for url. If you use WebAPI, it will be injected into your methods parameters.

Call c# function of global class from javascript

I have a global function that returns some string.
I need to access to that function from JavaScript in one of the pages and set returned value to JavaScript variable.
Example:-
var jsvariable = <%GlobalClass.MethodReturningString();%>;
How to do that?
You cannot call C# function like this. you need to create a web service or webmethod
in order to call this function.
Please see this link it will help you.
http://www.aspsnippets.com/Articles/Calling-ASPNet-WebMethod-using-jQuery-AJAX.aspx
Perform the following steps :
Right click on your website or web application and add a WebHandler. The extension for the webhandler is '.ashx'. Let's say you name your handler as 'Handler.ashx'
Open the Handler.ashx file and within the ProcessRequest method write the following :
context.Response.Headers.Clear();
context.Response.Write(GlobalClass.MethodReturningString(););
context.Response.Flush();
In your javascript, perform an ajax call using jQuery :
$.ajax({
url:'someUrl/Handler.ashx',
type:'GET',
success : function(data){
var someJavascriptVariable = data;
}
});
NOTE: This is a quick and dirty write so I'm not guaranteeing that the code will surely work, but it's a point for you to start with.
May i thick You cannot do this but u can access ur c# function using ajax
For Example
$.post('url', {parameter : parameter }, function (result) {
// here the result is your function return value or output
},"json");
URL FORMAT : '/pageurl/methodname'
First of all, as a clarification, it seems that you're not trying to actually call a C# method from Javascript, but rather render the return from a C# method inside the page so that it can be used as a Javascript variable value on the client side.
In order to do that you need to update you syntax like:
var jsvariable = '<%= GlobalClass.MethodReturningString() %>';
Please note that if your class is not in the same namespace as the inherited page from the code behind file, then you need to import its namespace like below:
<%# Import Namespace="GlobalClassNamaspace" %>
The namespace import can also be done globally (and it will be automatically available in all of the site's pages), using the web.config file as described here.
If you were to actually need to call a C# method from Javascript, which would have been needed if you wanted to dynamically use its results from client side code, then that could be accomplished through Ajax.

Update SQL Database from client side in ASP.NET

I am kinda new in web development, looking for secured way to update SQL Database from the client side, or in other description updating the database without refreshing the webpage like (like facebook button).
I searched a lot and found that it can be done by using a web service and call it by javascript or using javascript direct or ajax, but which is the best and secured way and there is any other way to do it ?
thanks..
you can use ajax for updating database from client side.. Like if you click a button in web page, get the click event of that page through JavaScript or jQuery then through ajax you can perform database update. See the code below:
For catching event(like my button id is button1):
$('#<%=button1.ClientID%>').click(function{
$.ajax({
type: "POST",
url: "default.aspx/UpdateDatabase",
data: "{'textboxvalue':'" + $('<%=textbox1.ClientID%>').val() + "'}'
contentType: "application/json;charset=utf-8",
datatype: "json",
success: UpdateDone
});
});
In above code you have passed one value from a textbox1 to function UpdateDatabse in Default.aspx page(Please defined this function as [WebMethod]). then do your update in this function and return some string or bool value so that you can judge that update is done then value in success is name of function that will run if your function runs successfully so define that function in JavaScript or jQuery like
function UpdateDone(response)
{
if(response.d == 'done')
{ alert('Update is done'); }
else
{ alert('Sorry Update not done'); }
}
Above code will not do any postback you see that your value is updated in database. Please note that the function you make in C# page please mark it as WebMethod and it will be a static method, then only your JavaScript can find that function.
Hope this will resolve your problem.
The term ajax you use is correct but already a bit old. The new kids on the block are called SPA's where SPA stands for Single Page Application
It does what you want to achieve to the extreme: no more page refreshes. So it seems a good way to start
Here is The ASP.NET Single Page Application homepage
My advice is to research and invest time in one of the (many) javascript frameworks that will help you achieve this goal much faster. Hand coding javascript and make it work cross browser is too much work. The ASP.NET team choose upshot.js to solve your problem and it seems a fine choice.
Screenshot take from here
I found doing AJAX with JSON with ASP.NET MVC 3 to be easiest method of doing AJAX requests. Then you can have a specific action method that handles the request and makes the updates the database via Entity Framework(EF).
Essentially only passing the data that needs to be updated in the JSON. From there the MVC Action receives the JSON, and uses EF to lookup the DB record, apply/save changes. It can even respond with a success message which your AJAX can use to update some field that verifies the data was saved for the user(you could even do something where you have a "Saving..." message appear between the first ajax request and the response.)
This will allow you to send the request without refreshing your page. All your DB access code will be server side in the Action method.
This example shows how you might do a json request. You would modify this by adding additional code to the Create method to interact with entity framework(or your database tool of choice) to update a record based on the Person person parameter that was passed in(notice MVC did a really nice thing of converting the json data into a nice Person class!)
http://juristr.com/blog/2011/08/posting-json-data-to-aspnet-mvc-3-web/
If the data the user will enter in the webform is sensitive, you would need to encrypt it before sending the json request. I would personally just setup the website to use SSL. Anything you cook up on your own probably won't be as secure as SSL.
The code you add to the Create method might look like this:
//Find the person that they are attempting to edit
Person currentPerson = db.Persons.Find(person.PersonKey);
//update the database fields based on the submitted data(I would probably actually use AutoMapper for this
currentPerson.Name = person.Name;
currentPerson.DateOfBith = person.DateOfBirth;
//etc.
db.SaveChanges();
//compose a JSON response object indicating success, you would want to combine this with a try catch in the above to reply regarding failures as well

Making an Ajax call in Umbraco from inside user control

For an Umbraco project, I am trying to make a simple Ajax call.. I can't use PageMethods because I need to make the call from inside a UserControl..
I tried to do it via web service call like this:
Web service method:
[System.Web.Script.Services.ScriptService]
public class MapService : System.Web.Services.WebService
{
[WebMethod]
public static string GetCities(string ProvinceCode)
{
return "foo";
}
}
JS part in my ASCX file:
<script language="javascript" type="text/javascript">
function callServer(src) {
MapService.GetCities(src, displayMessageCallback);
}
function displayMessageCallback(result) {
fillDDL(result);
}
</script>
The problem is, "MapService.GetCities" method doesn't get invoked..
What might be the problem here?
Alternatively, what is there any better way to make these kind of Ajax calls in a User Control?
I've been usign the Umbraco base REST Extensions for this kind of thing. I think it's a lot simpler to implement and if you use a JSON Serialiser on the server you even have proper JSON objects on the client.
Use REST method for doing this. we have implemented this for our projects. For this you have to edit the restExtensions.config and add your entry.
I think the problem might be that the javascript inside the usercontrol does not communicate with the scriptmanager in the page.
I can see two ways of dealing with this.
1. Use jQuery to call the webmethod instead of asp.net ajax.
2. through the control javascript call a method in the page javascript which will call the webmethod, i.e. use the page as a proxy. This has the added advantage of enabling you to use a page method instead of a web service.

Categories

Resources