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

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.

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.

Jquery all ajax calls not picking relative url - ASP.NET MVC

$(document).ready(function () {
getDefaultPDF();
loadPDF();
});
function loadPDF() {
$('#reportsDiv').load("/Review/DisplayPdfPartial");
}
Our site is hosted under the Default website, within a folder. So the url should be
http://servername/foldername/Review/DisplayPdfPartial
but the following code tries to fetch
http://servername/Review/DisplayPdfPartial - doesn't add the foldername and fails obviously.
This doesn't happen on local, only when deployed under default website.
What am I missing?
As you have mentioned you are using Asp.Net MVC then in that case instead of specifying url's this way, a more efficient way is to use #Url.Action() helper method as shown :-
$(document).ready(function () {
getDefaultPDF();
loadPDF();
});
function loadPDF() {
//$('#reportsDiv').load("/Review/DisplayPdfPartial");
$('#reportsDiv').load('#Url.Action("DisplayPdfPartial","Review")');
}
You can use ResolveClientUrl
A fully qualified URL to the specified resource suitable for use on
the browser.
Use the ResolveClientUrl method to return a URL string suitable for
use by the client to access resources on the Web server, such as image
files, links to additional pages, and so on
.

Cannot make a call to Page WebMethod using jQuery Ajax?

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]

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" });

Session state with jQuery/Ajax and ASP.NET web service

I'm trying to consume an ASP.NET web service, using jQuery's Ajax methods. I want the return type of the web service method to be JSON-formatted data, and I'm marking the method with these attributes:
[WebMethod(EnableSession = true)]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public MyObject[] GetMyObjects(int pageIndex) {/*...*/}
I want to also return from the method some sort of value that would indicate whether the session has expired, either in the SOAP headers an output parameter. How would I do this with jQuery syntax? Should I wrap my MyObject[] array in a serializable ResponseType object that contains a SessionValid property and the payload? Or is it possible to use SOAP headers and output parameters with jQuery?
Thanks.
Should I wrap my MyObject[] array in a serializable ResponseType object that contains a SessionValid property and the payload?
This is the way I usually go with.
Not time consuming to implement and very easy to maintain.
[Serializable]
public class MyReturn
{
public MyObject[] MyObjectList { get; set; }
public bool SessionExpired { get; set; }
}
Then handle it where you do the AJAX call.
EDIT: I usually only use
//...
contentType: "application/json; charset=utf-8",
dataType: "json",
//...
in my AJAX calls to be sure the returned type is in JSON format.
I'm not completely familiar with using session in SOAP web services. However, I did stumble on this post which states that the JavaScript will need to account for cookies since this is how the session is maintained.
Although, SOAP may use a different method for tracking session via it's headers, so I don't know if this is accurate.

Categories