This is my first time attempting to call an ASP.NET page method from jQuery. I am getting a status 500 error with the responseText message that the web method cannot be found. Here is my jQuery $.ajax call:
function callCancelPlan(activePlanId, ntLogin) {
var paramList = '{"activePlanId":"' + activePlanId + '","ntLogin":"' + ntLogin + '"}';
$.ajax({
type: "POST",
url: "ArpWorkItem.aspx/CancelPlan",
data: paramList,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function() {
alert("success");
},
error: function(xml,textStatus,errorThrown) {
alert(xml.status + "||" + xml.responseText);
}
});
}
And here is the page method I am trying to call:
[WebMethod()]
private static void CancelPlan(int activePlanId, string ntLogin)
{
StrategyRetrievalPresenter presenter = new StrategyRetrievalPresenter();
presenter.CancelExistingPlan(offer, ntLogin);
}
I have tried this by decorating the Web Method with and without the parens'()'. Anyone have an idea?
Your web method needs to be public and static.
Clean the solution and rebuild. I've seen webmethods throw 500's until you do this.
Add public static before your method...
ex.
[WebMethod]
public static string MethodName() {}
For ajax success:
For me, it was helpful to make:
App_Start\RouteConfig
set
from
settings.AutoRedirectMode = RedirectMode.Permanent;
to
settings.AutoRedirectMode = RedirectMode.Off;
make your using method:
public
static
add:
using System.Web.Services;
and on top of method using just:
[WebMethod]
is enough
First Of All Don't Forget To Include
using System.Web.Services;
And Make Sure Your Method Should Be Public And Static and avoid adding Multiple Scripts in same Page like jquerymin.js shouldn't be used for every Function/Method in same Page
[WebMethod]
public static sting MethodName(){}
I Had The Same Issue Which Using Ajax And Jquery To Check Username Exists
Or Not.
Related
This is a controller function:
public static void func(int id){
//some code
}
and this is a JavaScript function:
function notificationDivPressed(element,n) {
$(".NotificationDiv").removeAttr("style").children().removeAttr("style");
element = jQuery(element);
element.css("background", "#00b98d");
element.children().css("color", "white");
#MvcApplication.Controllers.MyController.func(n);
}
I want to do something like that... (use the "n" value a argument of "func" function from Controller)...
MVC controler are http paths you cannot call a function in the controller you need to call a post or a get Method. This can be accomplished using ajax
Small snipit
in controlerr create method that looks like this
[HttpPost]
public string Operation(string arg)
{
return "";
}
in View ".cshtml" you can call this using ajax
I usualy take the lazy way out and use jquery
$.ajax({
url: path to controler + '/Operation',
type: "POST",
cache: false,
data: {arg:'Argument Value'},
success: function (data)
{
}});
you could add error handling in the jquery if you like.
I am creating an asmx web service.
In visual studio 2012 on the project name I right clicked and added an web service name UserDetails.asmx
Now I am trying to use the web service in the js file. like this
$.ajax({
type: "POST",
url: "UserDetails.asmx/HelloWorld",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert('success');
},
error: function () {
alert("Error");
}
});
Its showing error that POST http: //192.168.9.185/GPS/UserDetails.asmx/HelloWorld 500 (Internal Server Error)
Is there any fault in my code or I am missing something so that its showing error.
My Asmx Page
<%# WebService Language="C#" CodeBehind="~/App_Code/UserDetails.cs" Class="UserDetails" %>
My Code Behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
/// <summary>
/// Summary description for UserDetails
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class UserDetails : System.Web.Services.WebService {
public UserDetails () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string HelloWorld() {
return "Hello World";
}
}
Edit
Short Answer: just uncomment [System.Web.Script.Services.ScriptService]
Digging deep in the error message by using
error: function (xhr,status, error) {
alert("Error");
}
and inspecting xhr revealed that the actual error was something else (Only Web services with a [ScriptService] attribute on the class definition can be called from script).
I used [WebMethod] in my aspx code behind and whenever I received such message, I found out that there was an error in the data I am passing. So try adding data:"{}", in your $.ajax()
as described in this post
When making a read-only request, the empty data parameter is the key. For reasons unknown, jQuery does not properly set the specified content-type when there is no data included.
I'm new to MVC, and I guess my confusion goes a bit beyond the title of this question, but for starters:
public class TestController : ApiController
{
[HttpPost]
public bool ReceiveHunk(Alterity.Models.Async.HunkDTO hunk)
{
return true;
}
[HttpPost]
public bool A(int x) { return false; }
[HttpPost]
public bool B(int x) { return true; }
}
I can't call my choice of A or B because it seems that the URL only routes to (is that the right term?) the controller, and the method is chosen based on the parameters. Since I have an (int x) on two methods, it doesn't know which to call. My confusion is exacerbated by the fact that when I do:
$.ajax({
cache: false,
type: "POST",
url: ApiLocation + 'Test',
contentType: 'application/json',
dataType: "json",
data: JSON.stringify(5),
success: function (response) { }
});
It still goes to the ReceiveHunk method, with the hunk being null. If I comment out B, ReceiveHunk is still called. Is this related to the fact that I'm using JSON instead of form url encoding? Do I have to have a separate ApiController for every method that has the same signature? Is there some way to configure the routing (or whatsit) to have the URL include the method name? A regular Controller includes the method name in the URL, why doesn't an ApiController? Furthermore, if I change either A or B take zero parameters, I simply get an internal server error (500) without any method being called and no exception. Any info that helps clear this up would be appreciated.
This is just the default routing convention for ASP.NET Web API, please read following question/answer for more details on how you can configure ASP.NET Web API routing (and have action names in routes):
Api controller declaring more than one Get statement
I have a registration form(Default.aspx) which initially show's only 2 field's and a button (Name, email) when user click's on button Jquery makes an Ajax call to Default.aspx.cs function which query db to check for the user, and if it return no then the form expands itself adding registration fields.
I am not able to make a call to Defualt.aspx.cs
my Default.aspx code is :
<script type="text/javascript">
$(document).ready(function() {
$('#btnDownload').click(function() {
//$('#secondary').toggle(1000)
$.ajax({
type: "POST",
url: "Default.aspx/PassData",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: AjaxSucceeded,
error: AjaxFailed
});
});
function AjaxSucceeded(result) {
alert(result.d);
}
function AjaxFailed(result) {
alert('Failed');
}
});
</script>
And Default.aspx.cs is (for test purpose) :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
private static string PassData(string id)
{
return "Pass";
}
}
But every-time I run the code JS returns error :
Uncaught ReferenceError: com is not defined
POST http://localhost:2305/temp/Default.aspx/PassData 500 (Internal Server Error)
I check few posts but non of them had been answered/resolved.
Any kind of help would be highly appreciated.
Thanks in advance
You need to decorate the method with [WebMethod] attribute.
EDIT
You'll need to add a ScriptManager and use some ASP.NET ajax framework methods. I think what you want to do is impossible with the out-of-the-box functionality.
One option will be to create a HttpHandler that will handle those methods. If the request is a POST, you can find the page type from the url (there's a method in the framework but I can't remember which one, you'll need to investigate), create a new instance and check if the method has the WebMethod (or another attribute you like). If it does, you can call it using reflection and render the result.
EDIT
As #Antony Highsky pointed out, it's possible. I think the solution is to add the [WebMethod] attribute and make de method public (it's private in the example).
Use **[WebMethod]
[WebMethod]
private static string PassData(string id)
{
return "Pass";
}
Why this WCF 3.5 method
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Json
{
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json)]
public string Upper(string text)
{
return text.ToUpper();
}
}
returns {"d":"TEXT"} ?
It should returns {"TEXT"}
I'm calling using jQuery.
$("#upper").click(function() {
$.ajax({
type: "GET",
url: "/Json.svc/Upper?text="+$("#input1").val(),
success: function(data) {
$("#input1").val(data.d);
}
});
});
This is a security feature that has been added to the JSON serialization in .NET 3.5. It's a container object, so instead of, say, results[0], you would just say results.d[0]. Read this article for more information.
I'm assuming you are using <enableWebScript/> in your behavior config, replace that with <webHttp defaultOutgoingResponseFormat="Json"/> and you will get json without the root "d" and without the "__type" props.
However, I've only tested this in 4.0
I also don't use any attributes in code.
Have you tried changing the BodyStyle property of your [WebGet] Attribute so that responses aren't wrapped?