How to call Handler (.ashx) from Jquery? - c#

I have a HTTP handler (.ashx) which generates some html code from database and I want to call it from my Jquery function and pass a value (userID).
I am not sure how to call it and retrieve its data.

something like this.
$(document).ready(function() {
$.get("http://path/to/handler.ashx", function(html) {
alert(html);
});
});

Use Google - first site after typing jquery ashx - https://sites.google.com/site/spyderhoodcommunity/tech-stuff/usingjqueryinaspnetappswithhttphandlersashx

Related

Can i link c# and html normally

Hello every1 I am both new to this site and html so i wanna ask Can i do something like that
<link href="index.cs">
then use functions If possible how ??
I want to use functions that i declare in my c sharp file fro a button
like i dont know
<button id="button-test" onclick="helloworld()">click</button>
and i ll have a function in c sharp named helloworld like
void helloworld()
{
return;
}
Thnx for ur answers
You can use javascript functions or use asp.net.
You can call the function in controller class using ajax like this
$("#buttonId").click(function (e) {
e.preventDefault();
$.ajax({
url: "/Controller/MethodName/{parameter}"
});
});
you should use ajax and connect to c# controller via ajax
Visit this link:
AJAX Introduction!
Take a look at using Blazor or Blazor WASM:
https://dotnet.microsoft.com/en-us/apps/aspnet/web-apps/blazor
You can use C# client side.

JavaScript not posting to the right action in ASP.NET MVC with implicit Index

When I surf to the address like this:
server:port/Controller
it automatically assumes that the action requested is Index, so the displayed page is equivalent to this:
server:port/Controller/Index
My problem is that when I execute something like this on a button click:
$(function () {
$("#clickaroo").click(function (event) {
event.preventDefault();
$.post("Action", null, function () { ... });
});
});
it fails when I'm at Index implicitly (i.e. page for that action is shown but the URL doesn't contain its name), while working when accessing it explicitly (i.e. URL says .../Controller/Index). If I then change the post into this:
$.post("Controller/Action", null, function () { ... });
it works for the former but starts to fail for the latter. Of course, I do understand why - location.href is suffixed by /Action and without the controller's name or with the name repeated, it gets confused. What's a best-practice way to handle that?
Horse around with RouteConfig.cs file? (sounds overkill)
Adding a condition in the JS? (feels as a baaad design)
Force the URL to be explicitly suffixed? (unsure how to)
The best solution is to use the Url.Action or Url.RouteUrl html helper method(s) to build the correct relative url to the action method. This will take care of building the correct url irrespective of the current page/view you are in.
var url1="#Url.Action("Create","Home")";
//use url1 now.
The above code will work if you have your javascript inside the razor views. If your script is inside an external file, You can build the relative url to the root and pass that to your js file and use that to build the url's as needed. Make sure to use javascript namespacing when doing so to avoid possible issues with global javascript variables.
So in your razor view (Layout file or specific view), you may do this.
<script>
var myApp = myApp || {};
myApp.Urls = myApp.Urls || {};
myApp.Urls.baseUrl = '#Url.Content("~")';
myApp.Urls.jobListUrl= '#Url.Action("Index","jobs")';
</script>
<script src="~/Scripts/YourExternalJsFile.js"></script>
And in your YourExternalJsFile.js file, you can read it like
var urlToJobIndex= myApp.Urls.jobListUrl;
// Or With the base url, you may safely add the remaining url route.
var createUrl= myApp.Urls.baseUrl+"home/create";
Edit : If you simply care about getting the root/base url of the site so you can append that to get the other url you are after, you may simply use / as the first character of your url.
var createUrl= "/home/create";
For your specific click event on an anchor tag use case, you can simply read the href attribute value of your link and use that.
If you want to make the ajax call to the same action method as the href attribute value of the link.
<a id="clickaroo" href="#Url.Action("Create","Customer")">Create<a/>
And in your click event get the href attribute value
$(function(){
$("#clickaroo").click(function(e){
e.preventDefault();
var u = $(this).attr("href");
$.post(u,function(response){
});
});
});
If you want to make the ajax call to the some other action method than the one in href attribute value of the link.
Here you can use data attribute to keep the other url in the link tag markup.
<a id="clickaroo" href="#" data-targurl="#Url.Action("Create","Customer")">Create<a/>
And in your click event get the data attribute value for "targurl"
$(function(){
$("#clickaroo").click(function(e){
e.preventDefault();
var u = $(this).data("targurl");
$.post(u,function(response){
});
});
});
You can use html5 attirbute as you have extetnal js files so razor will not be accessible there, use data- attribute on your button and then pick the url via jquery in the click handle like:
<button id="clickaroo" data-url="#Url.Action("Action","Controller")">Click me</button>
and then in js file:
$("#clickaroo").click(function (event) {
event.preventDefault();
var button = $(this);
$.post(button.data("url"), null, function () { ... });
});

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

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.

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.

Categories

Resources