I am having an issue hitting my C# WebMethod on the code behind and getting 500 internal server error. I don't really understand why it won't hit it so it would be really great if someone could tell me what is the problem.
So this is my ajax call and doesn't work even with data and datatype not commented out.
$('#chkBxAutoCost')
.click(function(e) {
$.ajax({
type: "POST",
url: "BatchReportCriteriaSelection.aspx/GetAutoJsonBatches",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: "{}",
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("Request: " +
XMLHttpRequest.toString() +
"\n\nStatus: " +
textStatus +
"\n\nError: " +
errorThrown);
},
success: function() { console.log("success") }
});
}
);
And this is my code behind method of the page:
[WebMethod]
public string GetAutoJsonBatches()
{
return autoJsonBatches;
}
So I have attached a breakpoint on this WebMethod and it's not being hit. I am pretty stuck so if someone had any insight I'd greatly appreciate it.
So as botond said in the comments my problem was that webmethods need to be static! Thanks very much was really wrecking my head!
First you have edit RouteConfig.cs and use
settings.AutoRedirectMode = RedirectMode.Off;
Next edit your GetAutoJsonBatches() to static
They're static because they are entirely stateless, they don't create an instance of your page's class and nothing is passed to them
in the request (i.e. ViewState and form field values).
HTTP is stateless by default, ASP.Net does a lot of stuff in the
background with ViewState, Session, etc. during a standard page
request to make life easier for developers.
Source
[WebMethod]
public static string GetAutoJsonBatches()
{
return autoJsonBatches;
}
To allow this Web Service to be called from script, using ASP.NET AJAX, you need to use [System.Web.Script.Services.ScriptService] attribute for your WebService.
[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public string GetAutoJsonBatches()
{
return autoJsonBatches;
}
}
And you haven't provided us what exactly is the exception message.
Related
Update
If I use Fiddler, I see I get a 200 OK Response but the following message:
{"Message":"Authentication
failed.","StackTrace":null,"ExceptionType":"System.InvalidOperationException"}
I have no idea where that's coming from.
Original Post
When I place a breakpoint in the web method it is never hit. The success handler runs for the ajax call. If I change the name of the url to incorrect value, I do get an error in F12 tools that it is not found.
I've tried EnablePageMethods='true' as well on the ScriptManager.
JavaScript lives in Scripts folder
$.ajax({
type: 'POST',
url: 'Tasks.aspx/UpdateStatus',
contentType: "application/json; charset=utf-8",
data: '{ id: 8, status: 1 }',
success: function (data) {
alert('it worked!');
},
failure: function (response) {
alert(response.d);
}
});
Tasks.aspx.cs code behind
[WebMethod(EnableSession = true)]
public static string UpdateStatus(int id, int status)
{
TaskManager taskManager = new TaskManager();
taskManager.UpdateStatus((TaskStatuses)status, id);
return string.Empty;
}
I ended up changing PageMethod in the code-behind to a web service asmx file and that seemed to have worked. Now I have to figure out how to secure it.
EDIT 2
I was able to solve the problem. There was nothing wrong with the Javascript or Controller code. The problem came from a .dll file. In the controller method I build a new TextInfo object from the TextModel object. The TextInfo object comes from a .dll that's build from the API. This .dll however had multiple instances with different build dates in the File System. Seems like the old version wasn't removed properly but it was the one the compiler used. This created a 500 Internal Server Error telling me that a Method wasn't available.
EDIT 1
I'm fairly certain my problem stems from a property in my model not being set correctly but I'm not sure why. I had 1 instance where I was able to debug though furhter into the code but I'm clueless as to why or how that happened. Will update later once I find more answers.
I am having trouble accessing the controller action from my ajax call and it honestly makes no sense to me as to why I'm unable to start the code. The issue seems to be with the CurrentPageNumber. When I comment out this variable from both c# and javascript, I am able to hit the breakpoint in the controller. But when I uncomment that variable I can't hit the breakpoint. The error I'm getting is 500 Internal Server Error. To me that sounds like the JSON keys aren't the same as the Controller parameters, but as you can see below that isn't the case (unless if I turned blind). Any idea what the problem could be? Prehaps I'm looking in the wrong direction?
tl;dr Controller ActionResult not started when CurrentPageNumber is in the parameter and key list (uncommented), but it does start when it isn't (commented out).
I am trying to reach the following ActionResult.
public ActionResult SavePageInfo(List<TextModel> TextObjects, string ImageSource, int CurrentPageNumber)
I do this with the help of the following AJAX call
var json = JSON.stringify({ TextObjects: textObjects, ImageSource: imageSource, CurrentPageNumber: pageNumber });
$.ajax({
url: "/NextprintPhotobook/SavePageInfo",
type: "POST",
data: json,
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function (data) {
console.log(data.message);
alert(data.message);
}
})
The JSON that's produced looks like this (as you can see all values are set):
"{"TextObjects":[{"text":"Test","x":50,"y":50,"fillColor":"#77DD44","fontFamily":"arial","fontStyle":"normal","fontSize":"18pt","fontWeight":"normal","textAlignment":"start","angle":0}],
"ImageSource":"http://localhost:22223/api/file/getfile?name=04.jpg&collectionId=4103&version=1&size=original",
"CurrentPageNumber":1}"
TextModel is as follows:
public class TextModel
{
public string text
{
get; set;
}
public int x
{
get; set;
}
public int y
{
get; set;
}
// Same properties as in the JSON.
}
Why are you not using a single object as parameter (a wrapper class for all those params)? (usually this is how it is done, unless you want to add some params in the query string also)
this is not the answer... well (i just want to put it here so its easier to read)
try this:
var data = {
TextObjects: JSON.stringify(textObjects),
ImageSource: imageSource
CurrentPageNumber: pageNumber
}
$.ajax({
url: "/NextprintPhotobook/SavePageInfo",
type: "POST",
data: data,
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function (res) {
console.log(res.message);
alert(res.message);
}
});
I've read many questions, forums, blogs, tried many things and I just can't seems to make it work.
I've tried using PageMethods.MyMethod() and that didn't work. Made sure my ScriptManager had EnablePageMethods ="true" and still nothing. I have a breakpoint on the server side and it never hits. Tried using ajax and still nothing
I'm 1st trying to understand how to make it work to then implemented on my program.
This is what I've tried so far:
Server-side:
[System.Web.Services.WebMethod]
public static void SomeMethod(string subject, string body, string recipients, string CurrentUserId)
{
MessageBox.Show("In c#");
}
JS:
function SomeFuntion()
{
debugger; alert("Before web service");
//PageMethods.CreateDraft(var1, var2, var3, var4);
$.ajax
(
{
type: "POST",
url: "NewMessage.aspx/SomeMethod",
data: "{subject:'" + var1+ "', body:'" + var2+ "', recipients:'" + var3
+ "', CurrentUserId:'" + var4+ "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success:
function()
{
alert("In ajax");
}
}
);
}
As you can see, I tried PageMethods and it didn't work. I know the function runs cause I see the alert message. By the way, the function is being called when the onclick event is fired of on a button. I don't get any errors and neither does it hit the break point on the MessageBox. This is new to me so any explanation would be very helpful too.
Check for errors from the server:
function SomeFuntion()
{
$.ajax({
type: "POST",
url: "NewMessage.aspx/CreateDraft",
data: "{subject:'" + var1+ "', body:'" + var2+ "', recipients:'" + var3+ "', CurrentUserId:'" + var4+ "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend:function ()
{
alert("about to send request");
},
success: function()
{
alert("In ajax");
},
error: function(xhr, status, error)
{
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
);
}
more additions
Since you are telling me that you are getting a "The HTTP verb POST used to access path '...' is not allowed" you might need configuration to enable .NET web service for http POST requests.
I have dropped .NET few years ago and therefore I have no direct experience but from what I could find in other sites you might need configuration at the server level such:
<system.web>
<webServices>
<protocols>
<add name="HttpPost"/>
</protocols>
</webServices>
</system.web>
Or directives above your method such
[ScriptMethod(UseHttpPost = true)]
public string SomeMethod()
{
....
}
I managed to figure it out with the help of a friend, I would post my answer but I believe it's quite long and complicated. I understood most of the things he did but I still didn't believe how it worked. It was pretty much almost the same thing I did but he made the JS in a separate file and set that file like a base JS. Called the web service there and from my JS he called that function that calls the web service. And it worked lol
I get the following error "Web Service method name is not valid" when i try to call webmethod from javascript
System.InvalidOperationException: SaveBOAT Web Service method name is not valid.
at System.Web.Services.Protocols.HttpServerProtocol.Initialize()
at System.Web.Services.Protocols.ServerProtocol.SetContext(Type type, HttpContext context, HttpRequest request, HttpResponse response)
at System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest request, HttpResponse response, Boolean& abortProcessing)
HTML Code :
<asp:LinkButton runat="server" ID="lnkAddBoat" OnClientClick="javascript:AddMyBoat(); return false;"></asp:LinkButton>
JS Code :
function AddMyBoat() {
var b = document.getElementById('HdnControlId').value;
jQuery.ajax({
type: "GET",
url: "/AllService.asmx/SaveBOAT",
data: { Pid: b },
contentType: "application/text",
dataType: "text",
success: function(dd) {
alert('Success' + dd);
},
error: function(dd) {
alert('There is error' + dd.responseText);
}
});
}
C# Code (Web method in AllService.asmx file)
[WebMethod]
public static string SaveBOAT(int Pid)
{
// My Code is here
//I can put anythng here
SessionManager.MemberID = Pid;
return "";
}
I tried all solutions found on Stack Overflow and ASP.NET site.but none of them worked for me.
It was a silly mistake.
remove Static keyword from method declaration.
[WebMethod]
public string SaveBOAT(string Pid)
{
SessionManager.MemberID = Pid;
return "";
}
In my case I had copied another asmx file, but not changed the class property to the name of the new class in the asmx file itself (Right click on asmx file -> View Markup)
In my case the error was that the Web Service method was declared "private" instead of "public"
Try using this, I think datatype should be JSON
jQuery.ajax({
type: "POST", // or GET
url: "/AllService.asmx/SaveBOAT",
data: { Pid: b },
contentType: "application/json; charset=utf-8",
dataType: "json"
success: function(dd) {
alert('Success' + dd);
},
error: function(dd) {
alert('There is error' + dd.responseText);
}
});
And in C# Code change Pid to string
[WebMethod]
public static string SaveBOAT(string Pid)
{
SessionManager.MemberID = Pid;
return "";
}
I too faced the similar issue. The solution includes checking everything related to ensuring all name, parameters are passed correctly as many have responded. Make sure that the web method name that we are calling in UI page is spelled correctly, the data, data types are correct and etc. In my case, I misspelled the web method name in my ajax call. It works fine once I found and corrected the name correctly.
For Ex: In .asmx class file, this is the method name "IsLeaseMentorExistWithTheSameName" but when I called from UI this is how I called:
var varURL = <%=Page.ResolveUrl("~/Main/BuildCriteria.asmx") %> + '/IsLeaseMentorExistWithSameName';
Notice that the word "The" is missing. That was a mistake and I corrected and so it worked fine.
As Sundar Rajan states, check the parameters are also correct. My instance of this error was because I had failed to pass any parameters (as a body in a POST request) and the asmx web method was expecting a named parameter, because of this the binding logic failed to match up the request to the method name, even though the name itself is actually correct.
[WebMethod]
public object MyWebMethod(object parameter)
If there is no parameter in the body of the request then you will get this error.
Did U add ServiceReference Class. Check this once. Based on your comment I can tell what to do
I had this issue because my soap method had a List<string> parameter. Couldn't figure out a way to make it work with the array parameter; so just converted the parameter to a &-delimited string (e.g. val1&val2&val3) and converted the parameter to an array in the service method.
In my case, one of the WebService receiving parameters was called aId. When I called it from javascript, I was sending the correct Id value, but the name of the sent variable was incorrectly called bId. So I just had to rename the WebService call, keep the correct value like before, and just change the variable name.
Earlier today I posted another post where #Darin Dimitrov helped me great, however once again I'm stucked...
My javascript calls the AddWebsite ActionResult which does it job as it should, however the error function in the $.ajax() is always firing since
return PartialView(ListPartialView, MapUserToViewModel);
isn't valid JSON.
I've come across examples where people use something like
RenderPartialViewToString(partialview, model);
and throws it into a JSON object... but it's just too "hackish" if you ask me.. isn't there an easier way to accomplish this?
... And the code:
// DashboardController.cs
[HttpPost]
public ActionResult AddWebsite(CreateWebsiteViewModel website)
{
if (!ModelState.IsValid)
{
throw new HttpException(400, "Client-side validation failed.");
}
if (string.IsNullOrWhiteSpace(website.URL))
{
throw new ArgumentNullException("URL", "The URL cannot be empty nor contain only whitespaces.");
}
using (_session.BeginTransaction())
{
_session.Query(new AddWebsite(_contextProvider.GetUserSession.UserId, website.URL));
_session.Transaction.Commit();
}
return PartialView(ListPartialView, MapUserToViewModel);
}
// MyJs.js
$("#testform").live('submit', function () {
var test = { URL: $("#URL").val() };
$.ajax({
url: "/Dashboard/AddWebsite",
type: "POST",
data: JSON.stringify(test),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("TRIG");
$("#content").html(data);
},
error: function () {
alert("Error");
}
});
return false;
});
Thanks in advance!
In your particular instance I think the problem is with your javascript code. You are specifying the dataType (which is what the function expects to parse in the response) as json. Based on the Action you posted you should have html as the dataType and it should solve your problem. There's nothing wrong with doing that (you don't have to use JSON for everything).
Simple data
Why are you setting dataType and contentType in the first place? Since your object test is very simple you can just provide it as is and it will be consumed by Asp.net MVC without any problems and you will return your partial view.
Complex data
If your object would be more complex then you could use a different jQuery plugin that will make it possible to send complex JSON objects without strigification.