JSON WebMethod not working in Sitefinity - ajax

I am trying to call via ajax a WebMethod hosted in a traditional ASP.Net WebForm code-behind page. Here is the code for the WebMethod:
[WebMethod]
public static object States()
{
StateProvince[] states = new StateProvince[] { };
ApplicationServiceClient proxy = null;
try
{
proxy = new ApplicationServiceClient();
states = proxy.GetStateProvinces();
}
finally
{
CloseServiceProxy(proxy);
}
return states;
}
The WebMethod works just fine in my stand-alone development environment or if deployed normally to IIS, but when I deploy the aspx page to Sitefinity, I get the following exception when it's called:
Server Error in '/' Application.
Unknown web method States.aspx.
Parameter name: methodName
I'm not sure if Sitefinity is hijacking the URL and post-pending the ".aspx" or what is going on here.
Here is the jquery call that is calling the web method:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Regions.aspx/States",
data: "{}",
success: function(data) {
// implementation omitted
},
error: function(xhr, msg) {
alert(xhr.responseText);
}
});
I can replicate the problem by posting the request manually using Fiddler.
Again, this works just fine everywhere except when deployed to Sitefinity. Anybody have any thoughts?

What version of .NET is Sitefinity running? Page methods are a recent addition.

use dataType: "json",

Related

asp.net web api methods are not getting executed

I am creating a web application in asp.net mvc with jQuery, I created a mvc application and included one web api controller, now my controller looks like the below
public class DefaultController : ApiController
{
[HttpGet]
[Route("Default/test")]
public string test()
{
return "1";
}
}
url of the application
https://localhost:44308/Home/about
but when I execute the method of my api the following error is coming
This site can’t be reached
I tried this with ajax call also but still the same problem
$.ajax({
type: 'GET',
url: 'https://localhost:44308/Default/test',
async: false,
global: false,
contentType: "application/json",
success: function (returnedData) {
console.log(returnedData)
}
});
I don't understand what I did wrong here
Change the route attribute
[Route("~/Default/test")]
public string test()
{
return "1";
}

Possible reasons for 500 internal server error in ajax call using aspx and c#

i am making an ajax call to fetch event for rendering a fullcalendar.
i am using a webmethod written in c#.
the ajax call is being made from an aspx page.
my site is a sharepoint 2010 site.
the calendar is being rendered using fullcalendar.js
i am facing the below issue :
the calendar works perfectly in most of the browsers and machines. but in some machine it doesn't render the events and when i look into the developer tool of the browser. it show me a
500 internal server error
in my ajax post call status.
can anyone tell me that what are the possible reasons for this error.
below is my call syntax along with the webmethod.
$.ajax({
url: 'PublicCauseList.aspx/GetCalendarItems',
type: "POST",
async: false,
data: data,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
}
},
error: function (error) {
console.log("Error in fetching calendar events.");
}
});
[WebMethod]
public static string GetCalendarItems(string courtSelected, DateTime start, DateTime end)
{
}
thanks

Dotnetnuke WebService with jquery Post

I am developing a dotnetnuke module and have lots of issues connecting to a webservice through javascript to retrieve data.
I have the folloiwng javascript:
function Test() {
$.ajax({
type: "POST",
url: 'http://localhost/DNN11/service1.asmx/TestMethod',
data: "{'data':'" + "abc" + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert("success");
},
error: function(e) {
alert("error");
}
});
}
Then the following WebMethod in my webservice
[WebMethod]
public string TestMethod(String data)
{
return "Hello World";
}
However when the post is not being called successfully, I am not able to get through my webservice. It keeps giving me a 500 Internal Server error page.
What could be wrong please? Is there any other way I need to go about this?
Thanks
[Edit]
This is the entire code
<script type="text/javascript">
function Test() {
$.ajax({
type: "POST",
url: '<%=ResolveUrl("~/DesktopModules/ModuleTest/WebService1.asmx/TestMethod")%>',
data: '{ data: "test" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert("Success: " + msg);
},
error: function(msg) {
alert("Failed: " + msg.status + ": " + msg.statusText);
}
});
}
</script>
<div>
<input type="button" value="Load" onclick="Test(); return false;" />
</div>
[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod()]
public string TestMethod(string data)
{
return "Hello World";
}
}
I have tried putting the Webservice in the DotNetNuke folder in a new folder and both in the local project.. I also put the ScriptMethod() Tag in the WebService which allows scripts to call it.. but still nothing
Looks like your problem is the cross domain calls. In case if your page hosted on the same server with the web service, your code should be fine. If you need to interact with the service from another domains you have to use jsonp requests. Look at this good step-by-step guide with the code example here.
UPDATE
In case if everything on the same app try to use relevant URL. Instead of url: '<%=ResolveUrl("~/DesktopModules/ModuleTest/WebService1.asmx/TestMethod")%>' try to url: '/DesktopModules/ModuleTest/WebService1.asmx/TestMethod'.
In order to post to a DNN webservice from the page you're going to have to pass in the Context of the module. I have some sample code that works against DNN6 at
http://slidepresentation.codeplex.com/SourceControl/changeset/view/69709#1181962
Mainly the
servicesFramework: $.ServicesFramework(<%=ModuleContext.ModuleId %>)
line
I haven't tested that against DNN7 though with the latest service framework WebAPI changes.

Asp .Net MVC4 website on IIS 7.5 gets HTTP 404 error in ajax error response

function girisAjaxKontrol() {
var kullanici = { 'kullaniciAdi': $('#username').val(), 'hidden': $('#password').val() };
$.ajax({
url: '/Giris/GirisGecerliMi',
type: 'POST',
data: kullanici,
success: girisAjaxReturn,
error: function (error, textstatus) {
JSON.stringify(error);
errorMessage($("div.girisSubmit input"), JSON.stringify(error), false);
}
});
}
This function gets the error below(it was working before deployment). The website is an Asp .Net MVC4 website on local IIS 7.5; I searched a lot but couldn't solve yet.
Server Error in Application \"DEFAULT WEB SITE\"
HTTP Error 404.0 - Not Found
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
Module: IIS Web Core
Notification: MapRequestHandler
Handler: StaticFile
Error Code: 0x80070002
Requested URL http://localhost:80/Giris/GirisGecerliMi
Physical Path C:\\inetpub\\wwwroot\\Giris\\GirisGecerliMi
Logon Method Anonymous
Logon User Anonymous
url: '/Giris/GirisGecerliMi',
should not be hardcoded like this. You should use url helpers to generate this url. The reason for that is because when you deploy your application in IIS there's a virtual directory name that you should take into account, so the correct url is:
url: '/MyAppName/Giris/GirisGecerliMi',
But by hardcoding the url as you did there's no way for this to work. In ASP.NET MVC you should always use url helpers such as Url.Action to generate the url to a given controller action as those helpers take into account not only your routing definitions but things like virtual directory names as well.
So the correct way is to have this url generated server side and passed as argument to the girisAjaxKontrol function:
function girisAjaxKontrol(url) {
var kullanici = { 'kullaniciAdi': $('#username').val(), 'hidden': $('#password').val() };
$.ajax({
url: url,
type: 'POST',
data: kullanici,
success: girisAjaxReturn,
error: function (error, textstatus) {
JSON.stringify(error);
errorMessage($("div.girisSubmit input"), JSON.stringify(error), false);
}
});
}

jQuery Autocomplete throws 401 - Unauthorised error while calling MVC 3 controller action method

I am getting "401 - Unauthorised" error in jQuery Autocomplete control in MVC3 application (.net framework v4.0.30319) which is deployed on a server containing IIS 7.5
Controller: (SearchSuggestController)
[HttpGet]
public JsonResult SuggestByEmployeeId(string Id)
{
var suggestions = from a in Context.Employees
where a.EmployeeId.Contains(Id)
select new
{
a.EmployeeId,
a.FirstName,
a.LastName
};
return Json(suggestions, JsonRequestBehavior.AllowGet);
}
jQuery: (Autocomplete)
$(function () {
$("#IDFilter").autocomplete({source: function (request, response) {
$.ajax({
url: "/SearchSuggest/SuggestByEmployeeId",
type: "POST",
dataType: "json",
data: { Id: request.term },
error: function (XMLHttpRequest, status, error) {
alert("Error status:(" + status + ") error:(" + error + ")");
},
success: function (data) {
response($.map(data, function (item) {
return { label: item.EmployeeId, value: item.EmployeeId,id: item.EmployeeId };
}));
}
});
},
minLength: 3,
autoFocus: true,
select: function (event, ui) {
$("#IDFilter").val(ui.item.value);
}
});});
jQuery is calling url: "/SearchSuggest/SuggestByEmployeeId" i.e. SearchSuggest controller's
SuggestByEmployeeId action.
Search.cshtml:(View)
#using (Html.BeginForm("BasicSearch", "Employee"))
{
#Html.Label("Employee Id:")
#Html.TextBox("IDFilter")
<input type="submit" value="Search" />
}
BasicSearch action method in Employee controller is working fine if valid EmployeeID is entered in "IDFilter" and clicked on Search button.
Autocomplete is showing expected results when i run the code through visual studio IDE. After publishing and Bin Deploying of this code to IIS 7.5 is throwing 401-Unauthorized error. The application is hosted under Default Web Site in IIS.
Anybody has any idea what is going wrong here?
You are AJAX POST to the action, but your action only accepts GET ?
Does your controller (or base controller) have the [Authorize] attribute?
I think i have got a solution.
Digging into jQuery using IE8 Developer Tools
On host server, the autocomplete XMLHttpRequest is trying to search for Request URL "http://localhost:80/SearchSuggest/SuggestByEmployeeId?Id=123"
But my application is hosted as "MyApp" under Default Web Site, so the URL should be like "http://localhost:80/MyApp/SearchSuggest/SuggestByEmployeeId?Id=123"
Hence i have updated the URL to url: "/MyApp/SearchSuggest/SuggestByEmployeeId"
After this change Autocomplete is fetching the expected results. 401 error is gone.
Probably in host environment, i will have to setup a new web site and bin deploy my MVC application under that.
This way i don't need to make this modification in jQuery everytime.
If anyone has got a better solution, please suggest.
To avoid issues with relative paths, rather than hard-coding the URL, use the #URL.Action helper.
So, your old code: url: "/SearchSuggest/SuggestByEmployeeId",
should become: url: '#Url.Action("SuggestByEmployeeId", "SearchSuggest")'
Good luck!

Resources