Yes, there are a whole bunch of posts with similar questions. I've tried to follow the answers in them, but my ajax call still isn't reaching the controller method.
controller (SalesController.cs):
[HttpGet]
public JsonResult fillVarietiesSelect(int species_id)
{
String[] alist = {"a","b","c"};
return Json(alist, JsonRequestBehavior.AllowGet);
}
javascript:
$('#species-select').on('change', function () {
var species_id = $('#species-select').val();
console.log("species id selected " + species_id);
alert("species id selected " + species_id);
$('#variety-select').empty();
$.ajax({
type: 'GET',
url: '#Url.Action("fillVarietiesSelect", "Sales")',
data: {species_id : species_id},
success: function (result) {
alert(result);
}
});
});
The on change event is firing, and the alert pops up with the correct data. I have a breakpoint set at the controller method, but execution doesn't seem to get there.
try doing exactly like following
Controller:
[HttpGet]
public ActionResult receive2(string p)
{
ViewBag.name = p;
List<string> lst = new List<string>() { p };
return Json(lst,JsonRequestBehavior.AllowGet);
}
Client side
$.ajax({
type: "GET",
url: "Main/receive2", // the method we are calling
contentType: "application/json; charset=utf-8",
data: { "p": $("#txtname").val() },
dataType:"json",
success: function (result) {
alert("yes");
alert('Yay! It worked!tim' + result);
window.location = "http://google.com";
// Or if you are returning something
},
error: function (result) {
alert('Oh no aa :(' + result[0]);
}
});
I have checked it's working
I had the same issue, changing the parameter from int to string resolved the problem.
On the server side I had,
public string RemoveByDocumentID(int DocumentID)
changing that to
public string RemoveByDocumentID(string DocumentID)
resolved the issue.
On the same context, I have another method in the same name (overloaded method). Which was also contributing to the issue, so I made the method name unique.
Your 404 error is telling you that #Url.Action is not being parsed by the view engine. The # is Razor syntax, so for this to work you need to be using a .cshtml extension for C# views or .vbhtml for VB views and be using MVC 3 or above.
Related
I have a method in MVC that I post to it and I need to return some data back to process.
This is my MVC method that I post to and return Value is a json data.
[HttpPost]
public JsonResult GetCalculateAmortizationSchedule()
{
var data = ...
var httpClient = new HttpClient();
var response = httpClient.PostAsJsonAsync("http://localhost:62815/v1/APR/CalculateAmortizationSchedule", data).Result;
var returnValue = response.Content.ReadAsAsync<Dictionary<int, AmItem>>().Result;
return Json(returnValue);
}
This is my AJax call that successfully run the MVC method.
$('#MyForm').submit(function (e) {
debugger;
$.ajax({
url: "/home/GetCalculateAmortizationSchedule",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
alert("success");
},
error: function (result) {
alert("error");
}
});
e.preventDefault();
});
My problem is how to catch the return value from method? when I run this after return Json(returnValue) the value is not returning to Ajax method and instead of seeing the Success Alert I see the error Alert.
Try this:
success: function (result) {alert(JSON.stringify(result)); }
From the error you have posted in comments below, it appears Dictionary is not serializable. Try setting AllowGet as mentioned in other answers. If doesn't work, you will need to convert Dictionary to some other object that is serializable. Or you may follow this to serialize Dictionary to json in your controller.
How do I convert a dictionary to a JSON String in C#?
You should add JsonBehavious if you are not getting values.
return Json(returnValue, JsonRequestBehavior.AllowGet);
Try this piece of code :
return Json(returnValues, JsonRequestBehavior.AllowGet);
I'm attempting to use jQuery in order to fire off an Ajax call after clicking a certain button. I've read several examples of the syntax and issues that may be encountered, but have failed to find a working solution for my cause. Here's the code.
Controller Method: (HomeController.cs)
[HttpPost]
public JsonResult ChangeCompany(string companyCode)
{
return Json(new { result = companyCode }, JsonRequestBehavior.AllowGet);
}
jQuery Code:
function changeCompany(company) {
$.ajax({
url: '#Url.Action("ChangeCompany", "Home")',
type: 'POST',
data: JSON.stringify({ companyCode: company }),
success: function (data) {
alert("Company: " + data);
},
error: function (req, status, error) {
alert("R: " + req + " S: " + status + " E: " + error);
}
});
}
And finally, I'm calling this function with:
$('.companyButton').click(function () {
compCode = $(this).text();
debug("Click event --> " + $(this).text());
changeCompany(compCode);
});
My debug message displays properly, and the Ajax call constantly fails with the following alert: R: [object Object] S: error E: Not Found
I'm not entirely sure what to make of that.
I know there are several questions on this topic, but none of them seem to resolve my issue and I'm honestly not sure what's wrong with these code blocks. Any insight would be appreciated.
EDIT:
In case it's worth noting, this is for a mobile device. Testing on Windows 8 Phone Emulator (Internet Explorer), alongside jQuery Mobile. Not sure if that affects Ajax at all
EDIT 2:
After taking a look at the raw network call, it seems that 'Url.Action("ChangeCompany", "Home")' is not being converted into the proper URL and is instead being called directly as if it were raw URL text. Is this due to an outdated jQuery, or some other factor?
Ok with your EDIT2 it seems you are using url: '#Url.Action("ChangeCompany", "Home")', in a separate JavaScript file. you can only write the razor code inside the .cshtml file and it is not working inside the .js files
You are missing some important parameters in your AJAX call. Change your AJAX call as below:
function changeCompany(company) {
$.ajax({
url: '#Url.Action("ChangeCompany", "Home")',
type: 'POST',
data: JSON.stringify({ companyCode: company }),
success: function (data) {
alert("Company: " + data);
},
error: function (req, status, error) {
alert("R: " + req + " S: " + status + " E: " + error);
}
});}
You can then annotate your controller method with [HttpPost] attribute as below;
[HttpPost]
public JsonResult ChangeCompany(string companyCode)
{
return Json(new { result = companyCode }, JsonRequestBehavior.AllowGet);
}
Note that your action is not returning companyCode directly. You're assigning it to Json result property therefore
In your success function to display result you need to have:
success: function (data)
{
alert("Company: " + data.result);
}
Also this: E: Not Found tells me that you may have some routing issues. If you set a break point inside of your ChangeCompany Action, is it being hit ?
When I ran below code for bttn click event it doesn't return a data for success method.
But it goes for controller method and return false (boolean value) as a out put.I need to pick that boolean value from javascript code.
Why it doesn't work ?
Javascript code is as below:
$('#btnClockInTime').off('click').on('click', function () {
var isClockOutTimeCompleted = true;
$.ajax({
url: "/Employees/IsClockOutTimeCompleted",
type: "GET",
dataType: "json",
cache: false,
data: { employeeId: employeeId },
success: function (data) {
if (!data) {
isClockOutTimeCompleted = data;
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
return false;
});
Controller Action Method is as below:
[HttpGet]
public JsonResult IsClockOutTimeCompleted(Guid employeeId)
{
var clockingDate = Convert.ToDateTime(DateTime.Today);
var isClockOutTimeCompleted = Repository.IsClockOutTimeCompleted(employeeId, clockingDate);
return Json(isClockOutTimeCompleted, JsonRequestBehavior.AllowGet);
}
Repository code is as below:
public bool IsClockOutTimeCompleted(Guid employeeId, DateTime clockingDate)
{
var clockOutTime = (from c in Catalog.EmployeeClockInOutTimes
where (c.Employee.Id == employeeId && c.Created == clockingDate && c.ClockOut == null)
select c).FirstOrDefault();
return clockOutTime == null;
}
UPDATE :
Response is as below :
UPDATE 2 :
Screen 1 :
Screen 2 :
Screen 3 :
As shown above images my debug doesn't come into success method.
After 2nd screen (when debug at error) it goes to controller and brings data.
3rd screen shows a status after returning from controller.Any idea ?
I would have thought that if you're return value is just false as a string then that will become your data value and as a result:
if (!data) { // won't fire }
As Darin says, if you wrap up your response Json inside an object and then use that to assign to your isClockOutTimeCompleted variable.
I wouldn't have thought you'd want to perform a boolean evaluation of your return value if it's a true/false return type, wouldn't you just want to assign it to isClockOutTimeCompleted either way?
if ur posting data to a controller method always use
'type':'POST' in ur ajax call &
change the [HTTPget] attribute from ur controller method to [httpPost]
below is my sample code which works fine
$.ajax({
url: 'Home/temp',
type: 'POST',
dataType: "json",
data: {'name':'surya'},
success: function (data) {
console.log(data);
//here i'm getting the data which i have passed
},
error: function () {
console.log("inside error")
}
});
and my controller code
[HttpPost]
public JsonResult temp(string name) {
return Json(name);
}
i'm getting back the data which i have passed in to the controller method via my jquery ajax..
may be u ought to change ur 'IsClockOutTimeCompleted' method where u are performing linq queries.just validate ur linq queries once..and also employeeId which ur passing into the controller is of type integer then instead of GUID as a parameter why dont u change the parameter type as int and see..
Regards
Before adding any parameters I had this POST method hitting my serverside code whenever a user would set focus from one control to another. This was good but i need to pass data of the id and value. These values are being populated from what gather in my failure growl.
The issue is that I don't exactly know why it will no longer hit my serverside routine. I did look around stackoverflow a good deal for some help, i did clean up a few things but I couldnt quite pinpoint exactly where my issue is.
$(document).ready(function () {
var id;
var value;
$(".tpControl").blur(function () {
id = this.id;
value = $(this).val();
var postdata = { identifier: id, controltext: value };
$.ajax({
type: "POST",
url: "TimePoints.aspx/ClientSideSave",
contentType: "application/json; charset=utf-8",
data: postdata,
dataType: "json",
success: function (msg) {
if (msg.hasOwnProperty("d")) {
OnSuccess(msg.d);
} else {
OnSuccess(msg);
}
},
error: OnFailure
});
});
function OnSuccess(result) {
$.growlUI('AutoSave Successful');
}
function OnFailure(result) {
$.growlUI("ID: " + id, "Answer: " + value);
}
});
My Server side is pretty simple
[WebMethod]
public static void ClientSideSave(string identifier, string controltext)
{
//Bunch of code, shouldn't affect anything.
}
Thank you in advance. Any help would be great, im pretty new to the world of Jquery and Ajax.
You were close, but remember you are posting JSON, not form value collections. This means JSON strings are quoted during transport and in your example, will be quoted on the backend, probably not what you really want:
var postdata = "{ 'identifier': 'id', 'controltext': 'value' }";
3 mistakes to avoid when using jQuery with ASP.NET AJAX
If you want use JSON(JavaScript Object Notation) the right way, then you should follow this example:
Using complex types to make calling services less… complex
I have this controller method:
public JsonResult List(int number) {
var list = new Dictionary <int, string> ();
list.Add(1, "one");
list.Add(2, "two");
list.Add(3, "three");
var q = (from h in list where h.Key == number select new {
key = h.Key,
value = h.Value
});
return Json(list);
}
On the client side, have this jQuery script:
$("#radio1").click(function() {
$.ajax({
url: "/Home/List",
dataType: "json",
data: {
number: '1'
},
success: function(data) {
alert(data)
},
error: function(xhr) {
alert(xhr.status)
}
});
});
I always get an error code 500. What's the problem?
Thank you
If you saw the actual response, it would probably say
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.
You'll need to use the overloaded Json constructor to include a JsonRequestBehavior of JsonRequestBehavior.AllowGet such as:
return Json(list, JsonRequestBehavior.AllowGet);
Here's how it looks in your example code (note this also changes your ints to strings or else you'd get another error).
public JsonResult List(int number) {
var list = new Dictionary<string, string>();
list.Add("1", "one");
list.Add("2", "two");
list.Add("3", "three");
var q = (from h in list
where h.Key == number.ToString()
select new {
key = h.Key,
value = h.Value
});
return Json(list, JsonRequestBehavior.AllowGet);
}
While JustinStolle's answer solves your problem, I would pay attention to the error provided from the framework. Unless you have a good reason to want to send your data with the GET method, you should aim to send it with the POST method.
The thing is, when you use the GET method, your parameters gets added to your request url instead of added to the headers/body of your request. This might seem like a tiny difference, but the error hints why it's important. Proxy servers and other potential servers between the sender and the receiver are prone to logging the request url and often ignore the headers and/or body of the request. This information is also often regarded as non important/secret so any data exposed in the url is much less secure by default.
The best practice is then to send your data with the POST method so your data is added to the body instead of the url. Luckily this is easily changed, especially since you're using jquery. You can either use the $.post wrapper or add type: "POST" to your parameters:
$.ajax({
url: "/Home/List",
type: "POST",
dataType: "json",
data: { number: '1' },
success: function (data) { alert(data) },
error: function (xhr) { alert(xhr.status) }
});