Send array of Objects to MVC Controller - javascript

I try to send an array of json objects to server:
var objectData = [
{ Description: "Bezeichnung", Value: "1", Name: "Betrag (Brutto)" },
{ Description: "Dies ist die erste Bezeicnung", Value: "101", Name: "11,90" },
{ Description: "Dies ist die zweite Bezeicnung", Value: "12", Name: "11,90" }
];
$.ajax({
url: "/system/createinvoice",
data: JSON.stringify({ pos: objectData }) ,
dataType: 'json',
type: 'POST',
});
C#
public class InvoicePos
{
public string Description { get; set; }
public Nullable<double> Value { get; set; }
public string Name { get; set; }
}
[POST("/system/createinvoice")]
public void newquestion2(InvoicePos[] pos)
{
// pos is always null
}

The dataType property is saying what you expect back from the server. Try setting the contentType:
contentType: 'application/json'

Try
data: JSON.stringify({ pos: #objectData })
Also, check what is being rendered in the View through the browser. The reason you are getting null is likely because JavaScript is not getting a proper value.

function SendArrayOfObjects()
{
var things = [{ id: 1, color: 'red' }, { id: 2, color: 'blue' }, { id: 3, color: 'yellow' }];
$.ajax({
type: "POST",
url: "<%= ResolveUrl("~/MyServices.aspx/GetData")%>",
data: JSON.stringify({ objdata: things }),
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function()
{
$("#msg").html("data sent successfully!");
},
error: function()
{
$("#msg").html(" Can not send data!");
}
});
}

Related

Unable to get array in controller from ajax

Not getting array of data from ajax to controller.
$.ajax({
type: "POST",
url: "/Home/List",
traditional: true,
contentType: 'application/json',
data: {
"Query": JSON.stringify(Query) //change this
success: function() {}
});,
And array of Query :
0: {label: "abc:", value: "123", type: "Select"} 1: {label: "xyz",
value: "Hum", type: "text"}
Can anyone help ?
Try something like this
<script type="text/javascript">
var query=[{label: "abc:", value: "123", type: "Select"},{label: "abc:", value: "1232", type: "Select"} ];
$.ajax({ type: "POST",
url: "/Home/List",
traditional: true,
contentType: 'application/json',
data: JSON.stringify(query),
success: function (){
} });
</script>
I think something along this may work for you.
function sendarray() {
var arr = [];
var json = {
"label": 'abc',
"value": 1234,
"Name": 'Name'
};
arr.push(json);
json = {
"label": 'abc2',
"value": 1234,
"Name": 'Name2'
};
arr.push(json);
var myarray = JSON.stringify(arr);
$.ajax({
url: '/controller/GetArray',
type: 'POST',
data: { array: myarray },
success: function (data) {
//Do something
},
error: function () {
//Do something
}
});
}
then in the controller
public JsonResult GetArray(string array)
{
var obj = JsonConvert.DeserializeObject<object>(array);
return Json("");
}
This will send an string with all the data in the array to the controller, then you turn string with json format into an object list

kendo ui core entity framework core undefined in kendoMultiSelect

UI looks like this
<div class="col-md-3">
<select id="kMultiSelect" data-placeholder="Select Traits..." />
</div>
Javascript
<script>
var dataSourceTraits = new kendo.data.DataSource({
transport: {
read: {
url: "api/Traits",
dataType: "json"
},
create: {
url: "api/Traits",
type: "POST",
dataType: "json",
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
},
schema: {
model: {
ID: "Trait",
fields: {
ID: { type: "number" },
UID: { type: "string" }
}
}
}
});
$("#kMultiSelect").kendoMultiSelect({
autoBind: true,
dataTextField: "UID",
dataValueField: "ID",
dataSource: dataSourceTraits
});
</script>
Model
public int ID { get; set; }
public virtual string UID { get; set; }
.....
Controller
// GET: api/Traits
[HttpGet]
public IEnumerable<Trait> GetTrait()
{
// var test = _context.Trait;
return _context.Trait;
}
I have 4 rows in my table and I get 4 rows in the kendoMultiSelect each row just has "undefined" for text.
Looks like this
thanks for the help
after more help, entity framework core, by default, returns json. this datasource works
var dataSourceTraits = new kendo.data.DataSource({
type: "json",
transport: {
read: {
url: "api/Traits"
}
},
schema: {
model: {
fields: {
id: { type: "number" },
name: { type: "string" }
}
}
}
});

Insert dynamic listbox options in Tinymce popup editor

I am trying to create dynamic listbox values but getting this error in console:
Uncaught TypeError: Cannot assign to read only property 'active' of [
Here's my code( pasting only the code for listbox ):
body: [
{
type: 'listbox',
name: 'type',
label: 'Panel Type',
value: type,
'values': get_author_list(),
tooltip: 'Select the type of panel you want'
},
]
.....
And I am calling this function to get dynamic list...
function get_author_list() {
var d = "[{text: 'Default', value: 'default'}]";
return d;
}
I am guessing that the values in listbox only takes static var and not dynamic. But I need to insert dynamic values in this list. Please can anyone help me find a workaround. Is there any possibility to insert via ajax?
Thanks, in advance!!
I needed something similar for .NET site. Even though is not great code I hope it can help someone.
tinymce.PluginManager.add('DocumentSelector', function (editor, url) {
// Add a button that opens a window
editor.addButton('DocumentSelector', {
text: 'Document',
icon: false,
title: "Document Selector",
onclick: function () {
var _documentList;
//load all documents
var _data = JSON.stringify({/* Some data */});
$.ajax({
type: "POST",
url: "/api/TinyMCE/GetDocuments",
data: _data,
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (data) {
_documentList = eval('(' + data + ')');
// Open window
editor.windowManager.open({
title: 'Document Selector',
body: [
{
type: 'listbox',
name: 'DocURL',
label: 'Documents',
values: _documentList
},
{
type: 'textbox'
, name: 'TextToDisplay'
, value: _text
, label: 'Text To Display'
},
{
type: 'textbox'
, name: 'TitleToDisplay'
, value: _title
, label: 'Title'
},
{
type: 'listbox',
name: 'TheTarget',
label: 'Target',
values: [{ text: 'None', value: "_self" }, { text: 'New Window', value: "_blank" }],
value: _target
}
],
onsubmit: function (e) {
// Insert content when the window form is submitted
}
});
},
error: function (xhr, status, error) {
alert("Error! " + xhr.status + "\n" + error);
}
});
}
});
});
And here it is some of the Behind code
public class TinyMCEController : ApiController
{
public class DocumentsInfo
{
// Some data
}
public class DocumentList
{
public string text { get; set; }
public string value { get; set; }
}
[HttpPost]
[ActionName("GetDocuments")]
public object GetDocuments(DocumentsInfo docInfo)
{
//Test data
List<DocumentList> _DocumentList = new List<DocumentList>();
_DocumentList.Add(new DocumentList {
text = "Document1.pdf",
value = "value1"
});
_DocumentList.Add(new DocumentList
{
text = "Document2.pdf",
value = "value2"
});
var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(_DocumentList);
return json;
}
}

Posting javascript array of objects to MVC4 controller

This is my controller action:
public ActionResult BrowsePartial(IList<SearchParam> searchParams = null)
{
//...
}
This is the object model:
public class SearchParam
{
public string Order { get; set; }
public string Type { get; set; }
public string Value { get; set; }
}
And here is how i send data to controller:
$.ajax(
{
type: "GET",
url: url,
data: { searchParams: [{ Order: "fghfdhgfdgfd", Type: "sasdsa", Value: "saddsadsads" }, { Order: "fghfdhgfdgfd", Type: "sasdsa", Value: "saddsadsads" }, { Order: "fghfdhgfdgfd", Type: "sasdsa", Value: "saddsadsads" }] },
mode: "replace",
cache: false,
});
Now, when i debug the action, i have an IList<SearchParam> that is correctly initialized with 3 elements. However, fields of each SearchParam object (Order, Type and Value) are initialized to null. What could be the problem here?
I think, the only way you can send your array parameter in a single request is to stringify it, and deserialize in your controller.
$.ajax(
{
type: "GET",
url: url,
data: { searchParams: JSON.stringify([{ Order: "fghfdhgfdgfd", Type: "sasdsa", Value: "saddsadsads" }, { Order: "fghfdhgfdgfd", Type: "sasdsa", Value: "saddsadsads" }, { Order: "fghfdhgfdgfd", Type: "sasdsa", Value: "saddsadsads" }])},
mode: "replace",
cache: false,
});
public ActionResult BrowsePartial(string searchParams = null)
{
SearchParam params = JsonConvert.DeserializeObject<SearchParam>(searchParams);
}
But I maybe mistaken ;)

Json data reading in client side in asp.net application

I have the following data as json:
"Table":[
{
"AF":2000.00
"RegionNumber":1
"RegionName":"Black Sea"
},
{
"AF":100.00
"RegionNumber":1
"RegionName":"Black Sea"
},
{
"AF":15000.00
"RegionNumber":2
"RegionName":"Istanbul"
},
{
"AF":31000.00
"RegionNumber":1
"RegionName":"Black Sea"
},
{
"AF":11000.00
"RegionNumber":2
"RegionName":"Istanbul"
}
]
I want to arrange the data in the following format in Javascript.
series: [{
name: 'Black Sea',
data: [2000, 100, 31000],
stack: 'Bookings'
}, {
name: 'Istanbul',
data: [15000,11000,0],
stack: 'Bookings'
}]
How can I accomplish this transformation?
This almost does what you ask and uses Ramda.js too
const data = {
Table: [
{
AF: 2000,
RegionName: "Black Sea",
RegionNumber: 1
},
{
AF: 100,
RegionName: "Black Sea",
RegionNumber: 1
},
{
AF: 15000,
RegionName: "Istanbul",
RegionNumber: 2
},
{
AF: 31000,
RegionName: "Black Sea",
RegionNumber: 1
},
{
AF: 11000,
RegionName: "Istanbul",
RegionNumber: 2
}
]
}
const transfromTableData =
R.pipe(
R.groupBy(R.prop("RegionName")),
R.map(R.pluck("AF")),
R.toPairs,
R.map(R.zipObj(["name", "data"]))
)
const transfromData = (data) => ({
series: transfromTableData(data.Table)
})
console.log(transfromData(data))
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>
In pure JavaScript:
var memo = {}
for (var i in table) {
var item = table[i];
if (memo[item.RegionName] !== undefined) memo[item.RegionName].data.push(item.AF);
else memo[item.RegionName] = {
name: item.RegionName,
data: [item.AF],
stack: 'Bookings'
}
}
var result = {
series: []
};
for (var i in memo) {
result.series.push(memo[i]);
}
console.log(result);
I'm passing arrays of custom objects into List in web methods and it works just fine.
I'm, guessing that you're having a small JSON formatting issue because of the quotes around the property names. Try changing your object to this :
var scoresList = [{TraitID:1, TraitScore:2}, {TraitID:2, TraitScore:5}];
and change your data line to this :
data: JSON.stringify({ scores : scoresList }),
Hope that helps...
UPDATE: working example...
<script type="text/javascript">
$(function () {
var scoresList = [{ TraitID: 1, TraitScore: 2 }, { TraitID: 2, TraitScore: 5}];
$.ajax({ type: "POST",
url: "Tryouts.aspx/Test",
data: JSON.stringify({ scores: scoresList }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (response.d == true) {
alert("success!!!!!");
} else {
alert("problem!!!!!!!!!");
}
},
error: function (xhr) {
alert("ERROR");
}
});
});
</script>
Here's the codebehind :
public class Score
{ // default constructor
public Score() { }
public int TraitID { get; set; }
public double TraitScore { get; set; }
}
[WebMethod]
public static bool Test( List<Score> scores )
{
return true;
}

Categories