Trouble sending an array to a model in MVC - javascript

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);
});

Related

Return parameter null in controller from ajax

I don't know what happened the value sent to the controller is always null, even though in the console.log the value is there, please I need help
this is my ajax:
$('#ddlItemName').change(function () {
var ItemCode = $('#ddlItemName').text();
if (ItemCode != '') {
var RequestParam = {
search: ItemCode
}
console.log(RequestParam);
$.ajax({
url: '/Order/CustomerItemOrders',
type: 'POST',
data: JSON.stringify(RequestParam),
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data[0].Name);
},
error: function (data) {
toastr.error(data);
}
});
}
$('#ddlItemName').text('');
});
This is my controller :
[HttpPost]
public JsonResult CustomerItemOrders([FromBody] string search)
{
var result = _order.BindCustomerOrders(search);
return Json(result.data);
}
This is my error :
enter image description here
I've tried adding '[FromBody]' but the value parameter still doesn't get sent
I recomend you add the parameter to query
If you insist on pass the value with request body
Try creat a model:
public class SomeModel
{
public string search{get;set;}
}
in your controller:
public JsonResult CustomerItemOrders([FromBody] SomeModel somemodel)
{
.......
}

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 });

Ajax call hits with null values

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.

Passing an array of Javascript classes to a MVC controller?

I am trying to pass an array of services to my controller.
I've tried a bunch of different ways to get it work, serializing the data before going to controller, serializing each service, only thing that seems to work is changing the controller parameter to string and serializing array, then using JsonConvert, but I'd rather not do that.
With the specified code, I am getting the correct number of items in the List, but they all contain a service id with an empty guild, and service provider id is null.
Any ideas?
Javascript
function ServiceItem() {
this.ServiceProviderID = 'all';
this.ServiceID = '';
}
var selecteditems= (function () {
var services = new Array();
return {
all: function() {
return services;
},
add: function(service) {
services.push(service);
}
};
})();
var reserved = [];
$.each(selecteditems.all(), function(index, item){
reserved.push({ ServiceID: item.ServiceID, ServiceProviderID: item.ServiceProviderID});
});
getData('Controller/GetMethod', { items: reserved }, function(result) {
});
var getData = function (actionurl, da, done) {
$.ajax({
type: "GET",
url: actionurl,
data: da,
dataType: "json",
async: true,
success: function (d) {
if (typeof (done) == 'function') {
var str = JSON.stringify(d);
done(JSON.parse(str));
}
}
});
};
Controller
public JsonResult GetMethod(List<CustomObject> items)
{
}
Custom Object
public class CustomObject
{
public Guid ServiceID {get;set;}
public Guid? ServiceProviderID {get;set;}
}
Set the content-type and use POST instead of GET (as it is a list of complex type objects). mark your action with HttpPost attribute too.
See if this works:-
$.ajax({
type: "POST",
url: actionurl,
data: JSON.stringify(da),
dataType: "json",
contentType: 'application/json',
async: true,
success: function (d) {
if (typeof (done) == 'function') {
var str = JSON.stringify(d);
done(JSON.parse(str));
}
}
});

Categories

Resources