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
Related
I have a Javascript code passing an object modeled exactly the same as my C# object
CreateItemModel. However, problem is in my Controller code a property that was set in javascript as new String(); gets deserialized to C# as null.
Javascript Code
$('[step="4"]').click(function () {
//shortened for brevety
var _model = new Object();
_model.ItemDesc = new String();
$.ajax({
type: "POST",
url: 'CreateItem',
data: _model,
success: function (msg) {
status = JSON.stringify(msg);
console.log(msg);
},
error: function (msg) {
status = JSON.stringify(msg);
console.log(msg);
}
});
});
C# Controller code
[HttpPost]
public async Task<JsonResult> CreateItemCallAsync(CreateItemModel item)
{
//breakpoint here
var test = item.ItemDesc; //the property is null here
}
I was expecting a string.empty value here but I am getting a null value instead. I tried setting the _model.ItemDesc to '' "" new String() in my Javascript code. But always getting a null value.
Questions:
Why is this behavior occurring?
How to get my expected value?
By default, the DefaultModelBinder will interpret empty strings as null. You can use the ConvertEmptyStringToNull property of DisplayFormatAttribute to have the property bind as an empty string.
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string ItemDesc { get; set; }
Try Changing the name item to _model
[HttpPost]
public async Task<JsonResult> CreateItemCallAsync(CreateItemModel _model)
{
//breakpoint here
var test = _model.ItemDesc; //the property is null here
}
Also Add contentType and dataType properties to your ajax request.
$.ajax({
type: "POST",
contentType: "application/json",
dataType: "json",
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 have to call and fetch data from rest API with in every second. So I call the method with time 1 sec. As follows.
var myVar = setInterval(function(){ getData1() }, 1000);
Following is my Javascript function which call the controller.
function getData1(){
var url=CONTEXT_ROOT+"/login/getdashboarddata1";
$.ajax({
type: "POST",
url: url,
contentType: "application/json",
dataType: "json",
data:{},
success: function(data){
alert(data);
},
error: function(e){
//alert(e);
}
});
}
This is my controller code
#RequestMapping(value="/getdashboarddata1", method=RequestMethod.POST)
public JSONObject #ResponseBody getDashboardData1() throws JsonParseException, JsonMappingException, NullPointerException{
RestTemplate restTemplate = new RestTemplate();
String url = "http://localhost:8080/r_f22bc0ac1fe48bce/dataService/lastdata/";
String user = restTemplate.getForObject(url, String.class);
System.out.println("user: "+user);
JSONObject obj = null;
try {
obj = new JSONObject(user);
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}
If I run the program then jsp does not shows any alert. but if I change the return type of in controller to String then it shows proper JSON string in ajax response.
i.e. [{"sno":"3618","data":"01","datetime":"2017-04-05 12:33:26.266"}]
If i carry this, then I am unable to get data from JSON string.
please tell me what is my issue. or is there any other way to do this.?
You have json array
[{"sno":"3618","data":"01","datetime":"2017-04-05 12:33:26.266"}]
Then access it using index:
data[0].sno
Simply return a String from getDashboardData1()
And then in AJAX success callback:
JSON.parse(data)[0]['sno'];
please tell me what is my issue. or is there any other way to do
this.?
You can't access attributes of a string literal, it has to be a json object.
I have a javascript function calling a JsonResult method, and the JsonResult method is sending the data back to the function, but when I test it with an alert in the javascript function it returns as Undefined. I have checked out a couple similar answers on SO, like this JsonResult returns null for Jquery .ajax and Jquery ajax not returning data [duplicate] but they are dealing with POST and not GET, can I get some guidance on what I am doing wrong or direction to where I can this figured out?
The end result is I need to get all the returned data from the JsonResult method then populate it into textfields.
My JsonResult method is..
public JsonResult myResult(string id)
{
dal = new AWDAL();
List<CustomerToAdd> cust = dal.GetCustomerByID(id);
return Json(cust, JsonRequestBehavior.AllowGet);
}
and my JavaScript is this..
function DataToGet(whatever) {
alert(whatever.customerName);
}
function GetCustomerByCustomerID() {
//var id = selectCustomerID;
var result = "";
$.ajax({
type: "GET",
url: "#Url.Action("myResult", new { id = "1234-5678-9012" })",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
return DataToGet(data);
}
});
}
I found this way of doing what I want but its for WebAPI2, I am not using WebAPI2 but it looks better, I am not even sure if I can use it to do what I want.
function formatItem(item) {
return item.Name + ': $' + item.Price;
}
function find() {
var id = $('#prodId').val();
$.getJSON(uri + '/' + id)
.done(function (data) {
$('#product').text(formatItem(data));
})
.fail(function (jqXHR, textStatus, err) {
$('#product').text('Error: ' + err);
});
}
EDIT
Response Header
Response Body
The payload is an array. To get a single item in the payload you would need to get it like so data[0] and each field data[0].customerName.
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.