get list response from ajax call c# - c#

I need to use the info from the list returned in a method that calls my ajax to c#.
This is the method, seems working fine:
public JsonResult getComandes(int id)
{
using (var db = new daw_tenda()) //estat 1 = acabat, estat 2 = en curs.
{
var llistacomandes = db.Comandes.Where(x => x.usuaris_id == id).ToList();
return Json(llistacomandes.ToList(), JsonRequestBehavior.AllowGet);
}
}
This is my ajax:
$.ajax({
url: "/Perfil/getComandes",
type: 'get',
dataType: 'json',
data: {
id: $("#idsesion").val()
},
success: function (response) {
$("#contingutcomandes").show();
$("#contingutperfil").hide();
if (response)
{
console.log(response);
}
}
});
I'm not getting any response, neither it's working first two jquery show and hide and i don't know what am i doing wrong, my method is working fine and is returning the list but i can't get it from the ajax call, what i have to fix?

Hmm -- since the method is correctly returning the list, the symptoms suggest the success function isn't being called. Have you tried changing success to complete? This'll execute even if the request is failing, which may shed some light.
Maybe something like:
complete: function(resp){
console.log("Ding!");
console.log(resp);
}

Related

Ajax Post not finding method in page model

I have the following method inside my page model which is called Order
public async Task<IActionResult> OnPostAddRecord(string recordId)
{
return new JsonResult("Hello");
}
My Ajax code to call said method:
$('#RecordList').change(function () {
var formData = {
recordId: $("#RecordList").val(),
};
$.ajax({
type: 'POST',
data: formData,
url: '#Url.Page("order", "addrecord")',
success: function (result) {
alert(result)
},
error: function (result) { }
});
});
Yet when it's fired it returns StatusCode 400, however, I have another Ajax method on the same page that works successfully, the difference is that one is a GET whereas this is a POST.
I really can't see what the problem is here.
You need to include the request verification token in your FormData: https://www.mikesdotnetting.com/article/336/ajax-posts-in-razor-pages-and-http-400-errors

HttpContext.Request.Form.Keys is empty when HttpContext.Request.HasFormContentType = true

This was working 2 days ago and now it's not and I cannot figure out why. I am submitting form data via ajax:
var mData = 'item=' + itemid + '&action=' + action;
$.ajax({
url: "/Admin/Home/Ajax",
type: 'POST',
contentType: 'application/x-www-form-urlencoded',
data: mData,
success: function (data) {
//Do Something
}
});
I have a method that process the incoming post:
if (HttpContext != null && HttpContext.Request.HasFormContentType)
{
foreach (var key in HttpContext.Request.Form.Keys)
{
QueryParams.Add(key, HttpContext.Request.Form[key]);
}
}
When the data is posted, HttpContext.Request.HasFormContentType is equal to true however, HttpContext.Request.Form.Keys.Count is equal to 0
I get no errors or anything. Any help or insight as to what is going on would be greatly appreciated.
This is a dotnet core 2.2 mvc web app.
Here is a working demo like below:
1.View:
<script>
var mData = 'item=' + 1 + '&action=' + "aaa";
$.ajax({
url: "/Home/Ajax",
type: 'POST',
contentType: 'application/x-www-form-urlencoded',
data: mData,
success: function (data) {
//Do Something
}
});
</script>
2.Action:
[HttpPost]
public void Ajax(int item,string action)
{
if (HttpContext != null && HttpContext.Request.HasFormContentType)
{
foreach (var key in HttpContext.Request.Form.Keys)
{
}
}
}
3.Result:
You are sending query data, not form data. Try sending it in a form like:
{
item: ...,
action: ...
}
Edit: Actually I was a bit surprised that it works while sending raw type of data and then passing in the query-like string. But the mearly fact that it works it doesn't mean it is a proper way of doing things. Foe example if You try to send API request from Postman (which I tried to reproduce Your error) I wasn't even able to perofrm such a thing as Postman asked me for key value pairs and interpreted a given query as a one key. Besides sending js object is more simpler that building a string.
I was also facing the issue of HttpContext.Request.Form.Keys is empty.
I just removed the .aspx extension from the request page and now the problem seems to be resolved for me.

jQuery ajax call doesn't seem to do anything at all

I am having a problem with making an ajax call in jQuery. Having done this a million times, I know I am missing something really silly here. Here is my javascript code for making the ajax call:
function editEmployee(id) {
$('#<%= imgNewEmployeeWait.ClientID %>').hide();
$('#divAddNewEmployeeDialog input[type=text]').val('');
$('#divAddNewEmployeeDialog select option:first-child').attr("selected", "selected");
$('#divAddNewEmployeeDialog').dialog('open');
$('#createEditEmployeeId').text(id);
var inputEmp = {};
inputEmp.id = id;
var jsonInputEmp = JSON.stringify(inputEmp);
debugger;
alert('Before Ajax Call!');
$.ajax({
type: "POST",
url: "Configuration.aspx/GetEmployee",
data: jsonInputEmp,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert('success');
},
error: function (msg) {
alert('failure');
}
});
}
Here is my CS code that is trying to be called:
[WebMethod]
public static string GetEmployee(int id)
{
var employee = new Employee(id);
return Newtonsoft.Json.JsonConvert.SerializeObject(employee, Newtonsoft.Json.Formatting.Indented);
}
When I try to run this, I do get the alert that says Before Ajax Call!. However, I never get an alert back that says success or an alert that says failure. I did go into my CS code and put a breakpoint on the GetEmployee method. The breakpoint did hit, so I know jQuery is successfully calling the method. I stepped through the method and it executed just fine with no errors. I can only assume the error is happening when the jQuery ajax call is returning from the call.
Also, I looked in my event logs just to make sure there wasn't an ASPX error occurring. There is no error in the logs. I also looked at the console. There are no script errors. Anyone have any ideas what I am missing here?
`
Try This
function editEmployee(id) {
$('#<%= imgNewEmployeeWait.ClientID %>').hide();
$('#divAddNewEmployeeDialog input[type=text]').val('');
$('#divAddNewEmployeeDialog select option:first-child').attr("selected", "selected");
$('#divAddNewEmployeeDialog').dialog('open');
$('#createEditEmployeeId').text(id);
//var inputEmp = {};
// inputEmp.id = id;
// var jsonInputEmp = JSON.stringify(inputEmp);
//debugger;
alert('Before Ajax Call!');
$.ajax({
type: "POST",
url: "Configuration.aspx/GetEmployee",
data: {id: id},
// contentType: "application/json; charset=utf-8",
// dataType: "json",
success: function (msg) {
alert('success');
},
error: function (msg) {
alert('failure');
}
}); }
if ajax call doesnot goes inside the success function then the problem is with your dataformat in CS code . the return data must not be in a proper JSON format . you should be getting "500" Error i guess.
Try returning it in a proper JSON format.

$.getJSON is not calling call back function

call back in not being called.
function GetTrainingResults(id,callback){
$.getJSON("/dashboard/GetTrainingResults/", {'id':id}, callback);
}
GetTrainingResults('id',function(result){
alert(result);
});
and code behind is
public ActionResult GetTrainingResults(int id)
{
string test = "You are there.";
return Json(test, JsonRequestBehavior.AllowGet);
}
Or suggest and another way. Task in to call controller method and wait for method response in javascript.
Thanks
If you use jQuery.ajax, you'll at least be able to see the error being returned by the server:
function getTrainingResults(id, callback) {
$.ajax({
url: "/dashboard/GetTrainingResults/",
data: {id: id},
success: function(data) {
callback(data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
callback(errorThrown);
}
});
}
id in your Action method takes an int, yet you're passing it a string of 'id' in your JS. Either change your JS or you action method so that the types match.
Check that your request is returning successfully, the ajax shorthand functions only call the callback if the request is successful (ie status code 200 and of the right data type, ie json). Try the full .ajax jquery function and see whats going on under the hood.
.getJSON() is equivient too
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
so it might be hitting error: due to the data type.
Source http://api.jquery.com/jQuery.getJSON/

jQuery $.ajax success not firing from JsonResult

My code makes an ajax call:
$.ajax({
url: "/Controller/EmailUserKeys",
dataType: 'json',
success: function () {
alert('success');
},
error: function () {
alert('error');
}
});
It calls an action in my controller which returns some JSON:
public JsonResult EmailUserKeys(string UserId)
{
...
return Json(new { success = true });
}
My problem is that the ajax error function is called and not the ajax success function.
Why?
PS. If my action returns "return null;", the ajax success function is called.
You must allow GET which is disabled by default when returning JSON results:
public JsonResult EmailUserKeys(string UserId)
{
...
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
or use a POST request:
$.ajax({
url: "/Controller/EmailUserKeys",
type: "POST",
dataType: 'json',
data: { userId: 'some user id' },
success: function () {
alert('success');
},
error: function () {
alert('error');
}
});
Also never hardcode the url to your controller action as you did. Always use url helpers when dealing with urls in an ASP.NET MVC application:
url: "#Url.Action("EmailUserKeys", "Controller")",
And here's a piece of advice: use a javascript debugging tool such as FireBug if you are doing any web development. Among with other useful things it allows you to inspect AJAX requests. If you had used it you would have seen the response sent from the server which would have looked like this:
This request has been blocked because sensitive information could be
disclosed to third party web sites when this is used in a GET request.
To allow GET requests, set JsonRequestBehavior to AllowGet.
And you wouldn't need to come to StackOverflow and ask this question as you would have already known the answer.
You should edit your code to this:
public JsonResult EmailUserKeys(string UserId)
{
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
See the official documentation for more info:
http://msdn.microsoft.com/en-us/library/system.web.mvc.jsonrequestbehavior.aspx
The reason for disabling this by default is because of JSON hijacking. More information about this can be found here:
http://haacked.com/archive/2009/06/25/json-hijacking.aspx
Hope this helps you out!

Categories