In Asp.net, 'Post' Ajax Request Will 'Get' - asp.net

In my Asp.net Project and in Controller with name 'AjaxController' I have this Action Method:
[HttpPost]
public ActionResult GetList(int year)
{
var res="";
// some codes
return Json(res);
}
And in Js file :
$.ajax({
url: '/Ajax/GetList/',
type: "POST",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
data: 2000,
async: false,
success: function (response) {
// some codes
},
error: function (xhr, status, error) {
alert(error);
},
});
I expect that this method ONLY called with 'POST' but when I check My logs I will see some errors like:
AbsoluteUri :https://example.com/Ajax/GetList/
* Message :A public action method 'GetList' was not found on controller 'Controllers.AjaxController'.
That shows Called as 'GET', NOT 'POST'.
What and where is problem?
Thancks In Advanced

Couple of suggestions from my end -
Remove contentType and async attributes unless really required
Pass JSON object to 'data'
Also, use debugger and breakpoints generously to figure out yourself where your code is going astray
$.ajax({
url: '/Ajax/GetList/',
type: "POST",
//contentType: "application/x-www-form-urlencoded; charset=UTF-8",
data: {year: 2000},
//async: false,
success: function (response) {
debugger;
// some codes
},
error: function (xhr, status, error) {
debugger;
alert(error);
},
});

Related

Calling asp.net 4.5 web service returns 302 and redirects to default page

$.ajax({
type: "POST",
async: false,
url: url,
data: dataParameters,
contentType: "application/json; charset=utf-8",
success: function (msg) {
//
},
error: function (xhr, ajaxOptions, thrownError) {
//
}
});
when using this in my local everything is fine but on host its return
[HTTP/1.1 302 Found 278ms]
my WS function :
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string SomeFunction(int something) {
//
}
The route was my problem. adding this line to route solve my problem :
routes.Ignore("{*allasmx}", new { allasmx = #".*\.asmx(/.*)?" });

X-editable with .Net and c# web methods

I am using X-Editable Plugin in Asp.net.
I have tried this: Usage with .Net and C# Webmethods
But it gives me error. It is not calling the WebMethod as it should be.
How to solve this problem?
Please help.
Javascript:
$('#username').editable({
url: function (params) {
return $.ajax({
url: 'Default.aspx/TestMethod',
data: JSON.stringify(params),
dataType: 'json',
async: true,
cache: false,
timeout: 10000,
success: function (response) {
alert("Success");
},
error: function () {
alert("Error in Ajax");
}
});
}
});
HTML:
superuser
WebMethod in Default.aspx:
[System.Web.Services.WebMethod]
public static String TestMethod(String params)
{
//access params here
}
If you want to call a page method, first of all you need to make a request of type POST (also having content-type set will not do any harm):
$('#username').editable({
url: function (params) {
return $.ajax({
type: 'POST',
url: 'Default.aspx/TestMethod',
data: JSON.stringify(params),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: true,
cache: false,
timeout: 10000,
success: function (response) {
alert("Success");
},
error: function () {
alert("Error in Ajax");
}
});
}
});
Also the JSON will be auto deserialized on server side, so you should expect the name, pk and value parameters on server side (this is what plugin is sending according to docs)
[System.Web.Services.WebMethod]
public static String TestMethod(string name, string pk, string value)
{
//access params here
}
In your case the pk will be null as you haven't set one.

jquery Post does not work in asp.net mvc 3?

I just copied some code from an asp.net mvc 2 app which works. Now i am trying it in asp.net mvc 3 and it does not call the save method on the controller?
controller:
[HttpPost]
public JsonResult save(string inputdata)
{
return Json(new { Result = string.Format("From the controller - you have clicked the GO-button ! ") }, JsonRequestBehavior.AllowGet);
}
view:
<button id="but">go</button>
<div id=result></div>
<script type="text/javascript">
$(document).ready(
$("#but").click(
function () {
$.ajax({
url: "/Home/save",
dataType: "json",
type: 'POST',
data: "test",
success: function (result) {
$("#result").html(result.Result);
}
});
}
)
);
</script>
You are not passing the data correctly. The action argument is called inputdata. So you should use this same name in the data hash of the AJAX request:
$.ajax({
url: '/Home/save',
dataType: 'json',
type: 'POST',
data: { inputdata: 'test' },
success: function (result) {
$('#result').html(result.Result);
}
});
Also never hardcode urls in your javascript, always use url helpers or your application will simply stop working when you deploy due to the possibility of having a virtual directory name:
$.ajax({
url: '#Url.Action("save", "home")',
dataType: 'json',
type: 'POST',
data: { inputdata: 'test' },
success: function (result) {
$('#result').html(result.Result);
}
});
Another issue that you have with your code is that you are not canceling the default action of the button meaning that if this is an action link or a submit button the AJAX request might never have the time to execute before the browser redirects.
Also you don't need to specify the dataType to JSON as jQuery is intelligent enough to deduce this from the Content-Type response header sent from the server.
So the final version should look something along the lines of:
<script type="text/javascript">
$(function() {
$('#but').click(function () {
$.ajax({
url: '#Url.Action("save", "home")',
type: 'POST',
data: { inputdata: 'test' },
success: function (result) {
$('#result').html(result.Result);
}
});
return false;
});
});
</script>

asp.net page method with jquery and parameter

In my javascript, I have:
var testdate = "{'TheNewDate' : '12/02/2011'}";
$("#mydiv").click(function () {
$.ajax({
type: "POST",
url: "../Pages/Appointments.aspx/GetAppointements",
data: testdate,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFn,
error: errorFn
});
});
In my code behind I have
[WebMethod]
public static string GetAppointements(string DateInput)
{
var t = DateInput;
However, when I click to run the call, I get the error function to activate. When I change the code behind function to public static string GetAppointement() it works. But I guess my goal is to pass a parameter to the code behind. What am I missing?
Thanks.
Your parameter is called DateInput and not TheNewDate, so:
$('#mydiv').click(function () {
$.ajax({
type: 'POST',
url: '../Pages/Appointments.aspx/GetAppointements',
data: JSON.stringify({ dateInput: '12/02/2011' }),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: successFn,
error: errorFn
});
});
You should make your JSON data match the parameter name in the web service method.
var testdate = "{'DateInput' : '12/02/2011'}";

Calling asp.net webmethod with params from jquery errors

I managed to setup a simple webmethod which i called from jquery and sure enough it returns ... then i added parameters on the method and added the params to jquery but it errors with
Message":"Invalid JSON primitive: one.","StackTrace":"
my signature on my webmethod is like so
[WebMethod]
public static string GetDate(string one, string two)
{
return "yes";
}
and my jquery is like this, what am i doing wrong?
$.ajax({
type: "POST",
url: "MyService.aspx/GetDate",
data: { one: "value", two: "value" },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg.d);
},
error: function(msg) {
alert('error');
}
});
Try enclosing your data parameter in quotes:
data: '{ one: "value", two: "value" }',

Resources