Javascript passing null to MVC Controller - javascript

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",

Related

Passing a list of strings in a Spring MVC controller using Jquery Ajax

i'm trying to pass a list of Strings to an MVC controller using JQuery Ajax, but i get the error No mapping for POST /myUrl/myContext/p
this is my jquery function:
$('#myButton').on('click', function(){
var strings = [];
$('#myForm input[type=checkbox]:checked').each(function(){
var string = $(this).closest('tr').find('#mySpan').text();
strings.push(string);
});
$.ajax({
url : 'myContext/p',
dataType : 'json',
type: 'POST',
data : {strings : strings},
success: function(response) {
//my success function
}
},
error: function(e) {
//my error function
}
}
});
})
this is my controller:
#PostMapping(value="/myContext/p")
public ResponseEntity<MyResponse> doPost(
#RequestParam(value="strings" ,required=true) List<String> strings)
throws Exception{
MyResponse response = new MyResponse();
//my Code
response.setData(strings);
return new ResponseEntity<MyResponse>(response, HttpStatus.OK);
}
I normally would use #RequestBody instead of #RequestParam for the strings parameter.
I fixed the issue with:
#PostMapping(value="/myContext/p", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE,
produces = {MediaType.APPLICATION_ATOM_XML_VALUE, MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<MyResponse> doPost( ArrayList<String> strings) throws Exception{
MyResponse response = new MyResponse();
//code
response.setData(strings);
return new ResponseEntity<RestResponse>(response, HttpStatus.OK);
}

controller can't return result in JSON object in ajax response

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.

Ajax call not reaching controller method

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.

Get servlet value in javascript and assign that value to a textbox using ajax

I am having a servlet where I am getting value from properties file. I want to get the value from servlet in my javascript and set that value to a textbox using AJAX. I am totally new to Ajax so please provide me a solution by looking at my code.
SERVLET
#WebServlet("/PopulateProperties")
public class PopulateProperties extends HttpServlet {
private static final long serialVersionUID = 1L;
Properties prop = new Properties();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String serverName=request.getParameter("servernameDD");
List<Map<String,String>> returnObj = new ArrayList<Map<String,String>>();
String[] servers = getSearchAttr("servers");
if (servers != null && servers.length > 0) {
String[] lookfor = getSearchAttr("servers_lookfor");
for (String server : servers) {
Map<String,String> obj = new HashMap<String,String>();
if (lookfor != null) {
for (String look : lookfor) {
//System.out.println("looking for :"+look);
String value = prop.getProperty(server+"_"+look);
if(server.equalsIgnoreCase(serverName)){
if(look.equalsIgnoreCase("Links")){
String getlook=prop.getProperty(look);
String getlink=prop.getProperty(server+'_'+look,"Links");
System.out.println("Hello" +getlink);
System.out.println(getlook);
request.setAttribute("serverLink", getlink);
}
}
if (value != null) {
obj.put(look, value);
}
request.setAttribute("servers", server);
request.setAttribute("lookfor", look);
}
}
//System.out.println("Object :"+obj);
returnObj.add(obj);
}
}
response.sendRedirect("updateserverstatus.html");
}
private String[] getSearchAttr( String property){
String lookfor = prop.getProperty(property,"");
String[] ret = {lookfor};
if (lookfor.contains(",")) {
return lookfor.split(",");
} else {
//System.out.println("comma not present in "+property);
//System.out.println("webservice :"+lookfor);
return ret;
}
}
I tried the following Ajax request but I am getting "serverLink undefined error"
function OnSelectionChange(){
$.ajax({
type: "POST",
url: "/PopulateProperties",
data: "{Links: " + serverLink + "}",
success: function(result){
alert(result.d);
console.log(result);
}
});
}
You use a servlet to get data and forward. It is not a proper way to provide data with servlet. A better solution is:
In your servlet, you should just return the properties data in a json format. You can refer this
Then you get this data with ajax in your html page, and update the text of textarea.
It is better to crerate separate servlet just for this purpose. This will keep your code coherent.
Pass all the parameter which will be used to narrow down to the data you need to retrive.
For simplicity just return the value or you can return the data as a JSON key value pair.
If your textbox is like this. <input type="text" id="prop_txt">
then the ajax code will be
$.ajax({
type: "POST",
url: "/PopulateProperties",
data: "{A:(..a value..),
B:(..b value..),
....
....
(..all the parameters required..)
}",
success: function(result){
//alert(result.d);
console.log(result);
$('#prop_txt').val(result);
}
});
Hope this heplps.

success method not fire on Ajax call

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

Categories