Cannot make a call to Page WebMethod using jQuery Ajax? - c#

I am currently trying to develop a chat applicaiton in asp.net2.0 and requires me to make a call to aspx Page Webmethod.My issue is that i cannot make a call to the page webmethod.
Not showing any message in error console of ff,so cannot findout where i have gone wrong.There is no issue while making a call webservice.
Heres the code i have writtern
$(document).ready(function(){
$("#btnSend").click(function(){
$.ajax({
type:"POST",
data:"{}",
url:"Chat.aspx/GetTime",
contentType:"application/json; charset=utf-8",
dataType:"json",
success:function(msg){
alert(msg.d);
},
error:function(msg){
alert(msg.d);
}
});
});
});
This is my chat.aspx page.The GetTime function is not getting called?Is the issue with the url ??
[WebMethod]
public static string GetTime()
{
return DateTime.Now.ToString();
}

Three things I would look at are:
1.) I'm wasn't sure that ASP.NET 2.0 could use the JSON AJAX stuff. I thought that came about in 3.5, but may be thinking of the ASP.NET AJAX implementation instead of jQuery's. See: Jquery's Ajax Property For Asp.Net 2.0, specifically:
You need to add this attribute to your webserver class
[System.Web.Script.Services.ScriptService]
public class Service : System.Web.Services.WebService
and this attribute to your functions
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
2.) You may want to check to see if the version of jQuery AJAX you are using is compatible with ASP.NET 2.0. I remember there being an issue there and needing to use older versions of jQuery (like 1.3) See: http://forum.jquery.com/topic/jquery-ajax-not-working-for-asp-net-2-0-7-5-2011
3.) This may be a long shot but is your page called Chat.aspx, or chat.aspx? Javascript capitalization matters (O;
Long shots, all of them, so good luck (:
[EDIT] Was just rereading the question and another idea popped in: Is the button from your .ASPX page? The reason I ask is because it's possible that when it's getting rendered on the page your button is no longer 'ID="btnSend"' but instead 'ID="ctl_btnSend_0897234h15807"' or so. If you have attached your jQuery to find '#btnSend' there's a chance that it's not the same ID in the DOM anymore.
Hoping that helps![/EDIT]

Related

ASP.NET MVC controller method called via getJson not working on server

Obligatory "This works in my dev environment, but doesn't work on the server."
I have an ASP.NET 5 MVC project, using .NET Core, in which actions taken on a certain view trigger a "getJson" call in my javascript code, which in turn calls a function on the controller to obtain data from the server, in order to update the page without a postback.
When a valid entry is made in a textbox, this function is called in my javascript:
function getCustomerOptions(cn) {
$.getJSON('/Home/GetBillingCustomerByCustNum', { cust: cn }, function (data) {
// handle returned json data
}
}
... which calls function GetBillingCustomerByCustNum in my Home controller:
public async Task<JsonResult> GetBillingCustomerByCustNum(string cust)
{
var data = //[retrieve data from server thru repository function]
return Json(data);
}
In my dev environment, this works great. But after I publish the application to an IIS environment on a Windows Server 2016 machine, this fails. It seems that IIS is trying to call '/Home/GetBillingCustomerByCustNum' as though it were a view or a physical object, and so returns a 404 error.
I have tried altering my getJson controller call -- jquery function "getCustomerOptions" -- by adding
<%= Url.Content("~/") %>
so that the call becomes
$.getJSON('<%= Url.Content("~/") %>/Home/GetBillingCustomerByCustNum', { cust: cn }, function (data) { ...
but that still fails. According to the debugger console, the above url is being translated as
http://localhost/HC_RFQ/Home/%3C%=%20Url.Content(%22~/%22)%20%%3E/Home/GetBillingCustomerByCustNum?cust=[given value]
The only other step I could find suggested I prepare my url with an HTML helper, like so:
var url = '#Url.Content("~/Home/GetBillingCustomerByCustNum/")'
$.getJSON(url, { cust: cn }, function (data) {...
but of course that fails because HTML helpers don't work in separate javascript files. Var url is passed in as literally written.
Finally, I know this is not a case of my javascript files not being linked properly, because I can breakpoint my javascript in the debugger ahead of this failing call, and the breakpoints are hit at runtime.
What else can I try to fix this? Any advice is appreciated.
Have you tried a simple Home/GetBillingCustomerByCustNum, just without the starting /? From how you describe the error in production, that's basically a server issue when composing the final route to the controller.
Dropping the Home/ part works because you're calling that action from a view that resides on the same controller's folder path. Since you're using .NET Core, I suggest using the asp-action and asp-controller tag helpers as they let the server decide what's the actual route to the desired methods, even if you're POSTing or GETing without an actual postbacks. For example, this is what I do using javascript to call my methods on a form:
<form asp-controller="myController" asp-action="myAction">
and this is how I get my js code to retrive the corresponding url
let form = $(this).parents('form')[0];
let url = form.getAttribute('action');
the form doesn't have an actual submit button, so that the calls are all made from javascript.

I have looked at calling c# through ajax, my implementation doesnt hit the c# method when I put a break point

My javascript to invoke the method in my c# class, the ajax call does get into success method but it does hit the c# method when I put in the break point. I tried changing the shoppingcart.aspx to shoppingcart.aspx.cs but still doesn’t hit the c# method.
<script type="text/javascript">
$('.removeCart').click(function (e) {
$.ajax({
type:"POST",
url: "ShoppingCart.aspx/deleteSelectedProduct/",
success: function () {
console.log("ITS GOING THROUH",e.target.dataset.removename);
},
error: function () {
}
});
});
</script>
my c# code
public void deleteSelectedProduct()
{
}
To troubleshoot
You should remove method name and put url of page as following
url: "ShoppingCart.aspx",
and put a break point on Page_load event if it hits the break point that means your url is fine now you can put complete url with method name.
url: "ShoppingCart.aspx/deleteSelectedProduct/",
Now you can check whats wrong with your method following are possible solutions
Your method deleteSelectedProduct should be static method
You'll need [WebMethod] decoration above your function deleteSelectedProduct
You'll need [WebMethod] decoration above your function in the aspx page.
I think you are missing starting / only. Correct the url like below:
url: "/ShoppingCart.aspx/deleteSelectedProduct/",
Give it try and let me know if it doesn't work.
The method you are trying to access using ajax call should be decorated with WebMethod attribute to enable ajax calling(#Dominic already suggested that, I am just describing it as a solution). It should be something like:
[System.Web.Services.WebMethod]
public void deleteSelectedProduct()
{
//implementation code
}
Or Include System.Web.Services as namespaces on top of the page and used directly WebMethod.
Cheers!!
You have to decorate the C# function with the WebMethod which will be in System.Web.Services.WebMethod.

How to deserialize in C# something that was serialized in JQuery?

. .
It's been a while since I've done this, and I'm trying to shake off the rust.
I'm trying to set up an AJAX structure in ASP.NET using VS2010.
I have a JQuery form submit that looks something like this (greatly simplified for example purposes):
function FormSubmit () {
$.post('SomeHandler.asmx/SomeFunction',
$("#form1").serialize(),
function(data) {some data handler}
);
}
My "SomeHandler.asmx/SomeFunction" is a C# function that takes my form data and processes it.
To my knowledge, the SomeHandler.asmx assumes XML deserialization, but the JQuery serializes it as an HTML encoded string, not as XML.
I suppose to use an analogy, one side is speaking in English, but the other side is expecting to hear French.
How do I get around this? (For example purposes, let's say my form has a text field -- we'll call it "txtField", and a drop-down list -- let's call it "lstDropDown".)
Thanks in advance for your help!
In your asmx file make sure you use the following attribute flags on your web methods that accept and respond with json:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string SomeWebMethod()
{
//blah
}
Also, make sure the web service class has the follow attribute flag:
[System.Web.Script.Services.ScriptService]
public class MyWebService : System.Web.Services.WebService
{
...
}
One last thing: if you're serializing the data on the client side, you need to use the following ajax setup:
$.ajaxSetup({ contentType: "application/json; charset=utf-8" });

ASP.NET: Web Service or WCF for simple ajax call?

I just want to simply call a method on my web service via ajax and have it return a value.
Should I use "WCF Service" , "AJAX-Enabled WCF Service" , or "Web Service"
Which is the easiest?
Use a generic HTTP handler instead. They are simpler to code.
You should use Ajax-Enabled WCF service. I don't remember the name exactly but it should be marked with an attribute to be accessible from JS.
You should never use the "Web Service" template unless you're maintaining existing code and can't change.
If you are just calling a single method use ScriptMethod
You can code it inline with the page that it is used on.
http://www.asp.net/ajax/tutorials/understanding-asp-net-ajax-web-services
Using the ScriptMethod Attribute
The ScriptService attribute is the
only ASP.NET AJAX attribute that has
to be defined in a .NET Web Service in
order for it to be used by ASP.NET
AJAX pages. However, another attribute
named ScriptMethod can also be applied
directly to Web Methods in a service.
ScriptMethod defines three properties
including UseHttpGet, ResponseFormat
and XmlSerializeString. Changing the
values of these properties can be
useful in cases where the type of
request accepted by a Web Method needs
to be changed to GET, when a Web
Method needs to return raw XML data in
the form of an XmlDocument or
XmlElement object or when data
returned from a service should always
be serialized as XML instead of JSON.
The UseHttpGet property can be used
when a Web Method should accept GET
requests as opposed to POST requests.
Requests are sent using a URL with Web
Method input parameters converted to
QueryString parameters. The UseHttpGet
property defaults to false and should
only be set to true when operations
are known to be safe and when
sensitive data is not passed to a Web
Service. Listing 6 shows an example of
using the ScriptMethod attribute with
the UseHttpGet property.
If those are your only options, I've found the AJAX-Enabled WCF Service to be the simplest to work with. It's still WCF, but it templates out for you the proper web.config setup and ditches the interface that the plain "WCF Service" template gives you. It seems to be the closest thing in the whole WCF mess to the old ASMX-style as far as being dirt simple to get going.
Just as another alternative, if you happen to be able to use ASP.NET MVC in your webforms project and just need this for an ajax call, you could skip the web service hoopla altogether and create a simple JSON result for your AJAX call like so:
// put this method in a controller
public JsonResult AjaxJsonTest(string who) {
var result = new {
Success = true,
Message="Hello, " + (who ?? "world!")
};
return Json(result, JsonRequestBehavior.AllowGet);
}
And then you can call it from jQuery like this:
<script language="javascript" type="text/javascript">
function AjaxTestClick() {
$.ajax({
type: "POST",
url: '<%: Url.Action("AjaxJsonTest", "Test") %>',
data: { who: 'whomever' },
success: function (resultData) {
if (resultData.Success) {
alert(resultData.Message);
}
else {
alert('Ajax call failed.');
}
}
});
}
</script>
Tons of options - pick what suits your situation best.

Execute an ASP.net method from JavaScript method

I have a javascript method looks like this
JSMethod(JS_para_1,JS_para_2)
{
......
,,,,,
}
and I have an ASP.NET method like this
ASP_Net_Method(ASP_Para_1,ASP_Para_2)
{
....
,,,
}
Now I want to call this ASP_Net_Method from my JSMethod by passing some parameters over there..
Just to be clear:
Your javascript is executed by the user's browser on the user's laptop
Your ASP.NET method is executed on your server
So, what you probably want to do is to send a message from the browser to the server saying "Hey, run this method and give me the result back".
If you are doing traditional ASP.NET development (not ASP.NET MVC), I think the normal approach would be to create an ASPX page which, when requested, executes the method you want executed. Then, in your javascript you just need to request this page. To do this, you can use jQuery (either jQuery ajax, jQuery get or jQuery post).
You will need to download the jQuery library and include it in your page for this to work.
Give it a go and if you can't get it to work, come back for more specific advice.
EDIT: You can also take a look at ASP.NET AJAX. The home page has a lot of tutorials and videos.
What you really want to do is execute server-side code (sometimes called "Code-behind", which was the term I used when googling this.) from javascript.
This post shows several options. The better ones are toward the bottom.
http://forums.asp.net/t/1059213.aspx
Basically, every function that fires a server side event uses a javascript method called __doPostBack and here is an example of what you want to do.
Ajax's PageMethods is very useful for this if you don't want to do a full postback and just need to call 1 method.
First I decorate a method in my aspx.cs file like so:
[System.Web.Services.WebMethod]
public static string getVersions(string filePath)
{ ...
return myString;
}
Notice the "static" too. Then in javascript I can call this like:
PageMethods.getVersions(_hfFilePath.value, LoadVersionsCallback);
You can have as many parameters as you need of different data types. The last parameter is the JavaScript function that gets called when the call returns. Looks something like:
function LoadVersionsCallback(result) {
...
// I make a drop down list box out of the results:
parts = result.split('|');
for (var i = 0; i < parts.length; i++) {
_ddl.options[_ddl.options.length] =
new Option(parts[i].replace(/~/g, ", "), parts[i]);
}
...
}
Finally, you must have the script managers property "EnablePageMethods" set to "true".
<ajaxToolkit:ToolkitScriptManager ID="ScriptManager1"
runat="server" EnablePageMethods="true"
EnablePartialRendering="true"
OnAsyncPostBackError="ScriptManager1_AsyncPostBackError">
</ajaxToolkit:ToolkitScriptManager>
So from JavaScript you can call a static function on your page's behind code.

Categories