Ajax call hits with null values - javascript

I have a array and I get data from the array and going to pass it to the controller through ajax call.
But the problem is it hits the controller side with all the null values.(Data not passes,null passes )
Client Side Code
for (var j = 0; j < NewsGlobalArray.length; j++) {
var NewsRequestModel = {
DESCRIPTION: NewsGlobalArray[j]['DESCRIPTION'] // news description comes here.i checked it with console.log
}}
$.ajax({
url: $('#addNewsRequest').val(),
type: "POST",
data: { newsRequest: NewsRequestModel },
dataType: "json",
success: function (referenceNo) {
//success
}
});
}
My Controller
[HttpPost]
public JsonResult AddNewsRequest(NewsRequestModel newsRequest) // hits here with null values
{
//Some coding goes here.
}
My Model
public class NewsRequestModel
{
public int NEWSREQUESTID { get; set; }
public string DESCRIPTION { get; set; }
}

Try this: just add traditional:true in ajax call
$.ajax({
type: "POST",
url: $('#addNewsRequest').val(),
data: JSON.Stringify({ newsRequest: NewsRequestModel }),
dataType: "json",
traditional:true,
success: function (res) {
//do something
}
});

I think you need to this:
var myObject = new Object();
myObject.name = "John";
myObject.age = 12;
then pass myObject to ajax call and get on controller by name.

Related

Ajax POST an object with javascript, but the value in backend is null, why?

So on button click there is a function sendEmail(). Alert is working fine, I can see my datas there. But on backend I can't see anything, just everything is null.
function sendEmail() {
var datas = new Object();
datas.mail = $('#contactDropdownList').val();
datas.mailobject = $('#emailObject').val();
datas.text = $('#emailText').val();enter code here
alert(datas.mail + datas.mailobject + datas.text);
$.ajax({
type: "POST",
dataType: "json",
url: "/Email/sendEmail",
contentType: 'application/json; charset=UTF-8',
data: JSON.stringify({ items: datas }),
success: function (data) {
console.log(data);
//do something with data
},
error: function (jqXHR, textStatus, error) {
//log or alert the error
console.log(error);
}
});
}
C# code:
public class MyClass
{
public string Email { get; set; }
public string Object { get; set; }
public string Text { get; set; }
}
[HttpPost]
public IActionResult sendEmail(MyClass items)
{
return Json(new { data="Ok" });
}
items.Email, items.Object and items.Text are null.
And the return valu is null as well, because in javascript success: function (data) { console.log(data);
is empty string.
What can be the problem? Thank you!
Model binder expects json content to match C# class. Your datas object should look like that
var datas = {
email: $('#contactDropdownList').val(),
object: $('#emailObject').val(),
text: $('#emailText').val()
}
Since you wrapped your object ({ items: datas }), you may think it will be mapped to sendEmail(MyClass items), but in reality items name does not matter, you can change variable name to any other name you like
Make sure you apply [FromBody] attribute to your parameter like that
[HttpPost]
public IActionResult sendEmail([FromBody]MyClass items)
Complete demo:
<script>
function sendSmth() {
var data = {
Email: 'email',
Object: 'object',
Text: 'text'
};
$.ajax({
type: "POST",
dataType: "json",
url: "/home/index",
contentType: "application/json",
data: JSON.stringify(data),
success: function (datas) {
console.log(datas)
}
})
}
</script>
And controller
[HttpPost]
public IActionResult Index([FromBody]MyClass obj)
{
return View();
}
As someone has noted, you have a mismatch between what you're sending to the controller and what the model the modelbinder is expecting. You can also vastly simply your AJAX code:
function sendEmail() {
var data = {
Email: $('#contactDropdownList').val(),
Object: $('#emailObject').val(),
Text: $('#emailText').val()
};
$.post("/Email/sendEmail", data)
.done(function (response) {
console.log(response);
//do something with response
})
.fail(function (jqXHR, textStatus, error) {
//log or alert the error
console.log(error);
});
}
You don't really need to specify the content type or data type - the $.post helper's defaults work just fine for what you've shown.

model is null when passed to ActionResult

Can anyone spot why my model would be null when it's passed to the controller? I put an alert in the ajax call to check the value there and it look correct, but a breakpointon the 1st line on the controller ActionResult shows it is null.
thanks in advance
ajax call
function DeleteFromList(_id) {
var _model = $('#createLPathForm').serialize();
alert(_model);
event.preventDefault();
$('#createLPathForm').validate();
if $('#createLPathForm').validate()) {
var request = $.ajax({
type: "POST",
url: "/umbraco/Surface/CreateLPath/DeleteItems",
dataType: 'json',
data: { 'model': _model, 'id': mId },
success: function (data) {
$("#lpPartial").html(data);
},
error: function (data) {
//$('#failModal').removeClass("d-none").addClass("d-block");
}
})
}
}
Controller
[HttpPost]
[ActionName("DeleteItems")]
public ActionResult ("DeleteItems")](CreateLPathModel _model, string id)
{
List<ModuleItems> items = _model.SelectedModuleList;
ModuleItems itemToDelete = new ModuleItems();
foreach (var item in items)
{
if (item.ArticleGuid == id)
{
itemToDelete = item;
}
}
_model.SelectedModuleList.Remove(itemToDelete);
itemToDelete.isSelected = false;
_model.SelectModulesList.Add(itemToDelete);
foreach (var key in ModelState.Keys.Where(m => m.StartsWith("SelectModulesList")).ToList())
ModelState.Remove(key);
foreach (var key in ModelState.Keys.Where(m => m.StartsWith("SelectedModuleList")).ToList())
ModelState.Remove(key);
return PartialView("~/Views/Partials/LearningPaths/_CreateLPath.cshtml", _model);
}
You are serializing your form and send as a property to your data model. In order to solve your problem, you can set data property with your _model variable and send your mId variable as query string :
function DeleteFromList(_id) {
var _model = $('#createLPathForm').serialize();
alert(_model);
event.preventDefault();
$('#createLPathForm').validate();
if $('#createLPathForm').validate()) {
var request = $.ajax({
type: "POST",
url: "/umbraco/Surface/CreateLPath/DeleteItems?id=" + mId,
dataType: 'json',
data: _model,
success: function (data) {
$("#lpPartial").html(data);
},
error: function (data) {
//$('#failModal').removeClass("d-none").addClass("d-block");
}
})
}
}
It can be done with:
Create a class with below structure:
public class RootObject
{
public CreateLPathModel _model {get; set;}
public string id {get; set;}
}
Then Controller method will be:
[ActionName("DeleteItems")]
public ActionResult ("DeleteItems")]([FromBody] RootObject obj)
{
// use Obj._model etc
}
and make sure while passing data in the AJAX call:
data: JSON.stringify({ 'model': _model, 'id': mId });

Passing Javascript variable to Java Controller (Spring-boot)

I'm new to this, so after I have read some solution about this but still not get it.
I have a var id = [] and want to pass it to my controller to delete it from database (SQL server)
My JavaScript
$('#deleteButton').click( function () {
var id = [];
var length = table.rows('.selected').data().length;
for(var i = 0; i < length; i++){
id.push(table.rows('.selected').data()[i][0])
}
$.ajax({
url: "",
//idk to put what into this url
//I think to put an url to show my var but i getting 404 and
//maybe im missing something in controller
//my url to access the project is: localhost:8084
method: 'POST',
data: {
idList: id
},
success: function (data) {
console.log(id);
}
});
console.log(id);
table.rows('.selected').remove().draw( false );
} );
My java controller
#Controller
#ComponentScans(value = { #ComponentScan })
public class CandidateController {
#Autowired
CandidateServiceImp candidateService;
//localhost:8084/manageCandidates is where i show datatable
//and var id = [] is getting from this table
#RequestMapping(value = { "/manageCandidates"})
public String manageCandidatesPage(Model model) {
model.addAttribute("listCandidates",candidateService.getAllCandidates());
return "manageCandidates";
}
}
Please instruct me to get var = id[] in controller
Thanks alot
There are three processes.
Add content-type: application/json in client-side ajax.
And enclose the data in JSON.stringify.
If the server-side Model is properly structured, add #RequestBody before the Model.
Use JSON:
Controller :
#RequestMapping(value = "/manageCandidates", method = RequestMethod.DELETE)
public #ResponseBody String manageCandidatesPage(HttpServletRequest request,#RequestBody String idjson) throws Exception
System.out.println("id"+idjson);
}
Ajax:- data: JSON.stringify(id),
$.ajax({
url: "",
type: "",
async: false,
processData: false,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(id),
success: function(data) {
response = data;
}
});

getting null value in list when passing by ajax call to mvc controller

I am passing my list to an mvc controller but I am getting null value in the controller.But my list has values when show in alert on client side.
ajax call
$("#addTiles").click(function() {
userTiles = JSON.stringify({
'userTiles': userTiles
});
alert("Entered function.");
alert(userTiles[0].TileID);
var url = '#Url.Action("AddTiles")';
$.ajax({
type: "GET",
url: url,
data: userTiles,
success: function(d) {
if (d.indexOf('"IsSessionExpired":true') != -1) {
location.reload();
} else {
onAddTilesSuccessful(d);
}
},
error: function() {
errorInOperation();
},
contentType: "application/html; charset=utf-8",
dataType: 'html'
});
});
function onAddTilesSuccessful(e) {
$("#tilesSubmissionMsg").append(e);
}
function errorInOperation(d) {
$("#tilesSubmissionMsg").append("Something went wrong");
}
mvc controller
public ActionResult AddTiles(List<UserTilesVM> userTiles)
{
return View();
}
List Model
public class UserTilesVM
{
public int TileID { get; set; }
public int TopPosition { get; set; }
public int LeftPosition { get; set; }
}
List in javascript
"{"userTiles":[{"TileID":"3","TopPosition":0,"LeftPosition":0}]}"
I have also tried by sending my list with stringfy but that also doesn't work.
Use : [HttpGet] on the method AddTiles as you have used type: "GET" on the Ajax hit.
[HttpGet]
public ActionResult AddTiles(List<UserTilesVM> userTiles)
{
return View();
}
If Still doesn't works then try type: "POST" on Ajax hit and on method use [HttpPost]
[HttpPost]
public ActionResult AddTiles(List<UserTilesVM> userTiles)
{
return View();
}
You have contentType and dataType twice in your AJAX setup, with different values, which will break the AJAX call.
Keep in mind contentType is to tell the server what type of data to expect and dataType is to determine what type of data is returned, from the documentation.
Edit: I see you have edited your code!
In this case, since you are using JSON.Stringify to modify the data you are sending, you would use contentType: "application/json; charset=utf-8", as your contentType, since you are sending JSON data to the backend.
when we are trying to pass object data using ajax, we have to store data in variable and pass data directly using "data :'variable'" in AJAX to Controller Method
$("#addTiles").click(function() {
var userTiles = ({
'userTiles': userTiles
});
alert("Entered function.");
alert(userTiles[0].TileID);
var url = '#Url.Action("AddTiles")';
$.ajax({
type: "POST",
url: url,
data: userTiles,
success: function(d) {
if (d.indexOf('"IsSessionExpired":true') != -1) {
location.reload();
} else {
onAddTilesSuccessful(d);
}
},
error: function() {
errorInOperation();
},
contentType: "application/html; charset=utf-8",
dataType: 'html'
});
});
function onAddTilesSuccessful(e) {
$("#tilesSubmissionMsg").append(e);
}
function errorInOperation(d) {
$("#tilesSubmissionMsg").append("Something went wrong");
}
//Use [HttpPost] keyword for getting value which was passed by AJAX.
[HttpPost]
public ActionResult AddTiles(List<UserTilesVM> userTiles)
{
return View();
}
I think your list definition is not ok:
"{"userTiles":[{"TileID":"3","TopPosition":0,"LeftPosition":0}]}"
should be:
"{"userTiles":[{"TileID":"3","TopPosition":"0","LeftPosition":"0"}]}"
i have using this sequence that work fine
you have check the
contentType: "application/json",
dataType: "json",
sequence in ajax method

Trouble sending an array to a model in MVC

What I have:
A Model like this:
public class ProductModel
{
public string ProductName { get; set; }
public List<string> SkipUpdates { get; set; }
}
A controller method like this:
public ActionResult GetProductUpdates(ProductModel productModel)
{
return View("AddEdit");
}
Not doing anything for now just want to make sure that data from JS comes in correctly.
The JS:
function productModel() {
this.productName = "";
this.SkipUpdates = [];
}
Filling the model and AJAX:
var newProductModel = new productModel();
var options = $('#AdditionalSkipDates option');
var skipDates = [];
options.each(function (i, option) {
skipDates[i] = $(option).text();
});
newProductModel.productName = "ABC";
newProductModel.SkipUpdates = skipDates;
$.ajax({
type: "GET",
url: urlToGetProductSchedule,
data: newProductModel,
dataType: "json"
}).success(function () {
}).fail(function (xhr) {
alert("Something went wrong!!!");
console.log(xhr.responseText);
});
AdditonalSkip dates is a listbox with a bunch of dates in it.
What's happening:
The SkipUpdates array does have values which I can see in the browser's console.
Put a breakpoint in the controller and it hits the method.
The SkipUpdates value is null.
What's not happening:
How do I get the array to come-into the controller?
Thanks in advance.
Try to stringify the object before sending it:
$.ajax({
type: "GET",
url: urlToGetProductSchedule,
data: JSON.stringify(newProductModel),
dataType: "json"
}).success(function () {
}).fail(function (xhr) {
alert("Something went wrong!!!");
console.log(xhr.responseText);
});

Categories

Resources