Want to Save Posted Json data to database - asp.net-mvc

I am posting JSON data through AJAX POST as ::
var length = $('.organizer-media').length;
var contents = $('.organizer-media');
var Title;
type == "New" ? Title = $('#newName').val() : Title = $('#Playlist option:selected').text();
var playlistid = $('#Playlist').val()
type == "New" ? playlistid = 0 : playlistid = $('#Playlist').val()
var data = [];
for (var i = 0; i < length; i++) {
data[i] = { ID: parseInt(contents[i].id), MetaID: parseInt(contents[i].title) }
}
var totaldata={ data: data, playlistid: parseInt(playlistid),Title:Title };
$.ajax({
type: 'POST',
data: JSON.Stringify(totaldata),
url: '/Builder/Save',
success: function () {
alert("Playlist saved successfully!!");
}
})
the JSON data is sent in following format::
{"data":[{"ID":779389,"MetaID":774367},{"ID":779390,"MetaID":774367},{"ID":779387,"MetaID":774366},{"ID":779388,"MetaID":774366},{"ID":779386,"MetaID":774365},{"ID":779385,"MetaID":774364},{"ID":779384,"MetaID":774363},{"ID":779383,"MetaID":774362},{"ID":779382,"MetaID":774361},{"ID":779381,"MetaID":774360},{"ID":779378,"MetaID":774359},{"ID":779379,"MetaID":774359},{"ID":779377,"MetaID":774358},{"ID":779376,"MetaID":774357},{"ID":779375,"MetaID":774356},{"ID":779372,"MetaID":774355},{"ID":779373,"MetaID":774355},{"ID":779374,"MetaID":774354},{"ID":779370,"MetaID":774353},{"ID":779394,"MetaID":774370}],"playlistid":1461,"Title":"MX OPEN TALENT MARIA"}:
and as I made an ItemViewModel as ::
public class ItemEditViewModel
{
public long ID { get; set; }
public long MetaID { get; set; }
}
and My controller code is as::
[HttpPost]
public ActionResult Save(ItemEditViewModel[] data,long playlistid=0, string Title="")
{
for (int i = 0; i < data.Length; i++)
{
var pc = db.PlaylistContents.FirstOrDefault(x => x.PlaylistContentId == data[i].ID);
if (pc == null)
{
pc = new PlaylistContent();
db.PlaylistContents.Add(pc);
}
pc.ContentMetaDataId = data[i].MetaID;
pc.PlaylistContentSequenceId = i + 1;
}
db.SaveChanges();
return Json(new { foo = "bar", baz = "Blech" });
}
while Execution of data in controller it doesn't accept the POSTED data as its ViewModel values.

My Problem is solved.
As I have Posted array in combination with two other variables, I just need to stringify array & not the whole ajax data which is to be posted.
as you can see in my code below::
var totaldata = { data: data, playlistid: parseInt(playlistid), Title: Title };
$.ajax({
type: 'POST',
data: { data: JSON.stringify(data), playlistid: parseInt(playlistid), Title: Title, deleted: JSON.stringify(deleted) },
traditional:true,
url: 'Save',
success: function (data) {
alert("Playlist saved successfully!!");
}
})
In above code I have just done stringify on array & not on other data.
Thanks for some Co-operations of yours.

Related

Pass (Send) Json string to Controller using jQuery AJAX in ASP.Net MVC

I am having trouble passing the data to the controller. Here is my code below.
Javascript:
let memberID = $("#MemberID").val();
const element = document.querySelectorAll('[index-id]');
let imax = element.length;
let SOData = `{MemberID: ${memberID}, SalesOrderDetails:[`;
let i = 0;
let salesOrders = [];
while (i < imax) {
let ubound = 5;
let indexid = element[i].attributes["index-id"].nodeValue;
let prodID = element[i].attributes["selected-id"].nodeValue;
console.log("prodID: " + prodID);
let quantity = 0.00;
let unitPrice = 0.00;
let tax = 0.00;
for (x = 1; x <= ubound; x++) {
let value = element[i].value;
if (x == 2) {
quantity = value;
}
else if (x == 3) {
unitPrice = value;
}
else if (x == 4) {
tax += value;
}
i += 1;
}
salesOrders.push(
{
"ProductID": parseInt(prodID),
"Quantity": parseInt(quantity),
"UnitPrice": parseFloat(unitPrice),
"Tax": parseFloat(tax),
"Discount": 0.00,
}
)
}
$.ajax('/SalesOrder/CreateOrder', {
method: 'post',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: { SalesOrderDetail: JSON.stringify(salesOrders) },
traditional: true,
success: function (d) {
console.log(d);
}
});
This is my code on the Controller:
[HttpPost]
public ActionResult CreateOrder(List<SalesOrderDetail> SalesOrderDetail)
{
//This is the controller
return null;
}
Here is my Class that I used:
public class SalesOrderDetail
{
public int ProductID { get; set; }
public int Quantity { get; set; }
public decimal UnitPrice { get; set; }
public decimal Tax { get; set; }
public decimal Discount { get; set; }
}
Please let me code what the issue is. It seems that there is no value that has been passed to the controller.
salesOrders is defined as arrry [], so then you use JSON.stringify to convert it to a JSON object, there's no key name for this array, and that's the reason why your controller can't get the list data. You should remove contentType and JSON.stringify.
$("#btn2").click(function(){
var salesOrders = [];
var obj = {
"ProductID": 123,
"Quantity": 1,
"UnitPrice": parseFloat("12.7"),
"Tax": parseFloat("0.2"),
"Discount": 0.00,
};
var obj2 = {
"ProductID": 124,
"Quantity": 2,
"UnitPrice": parseFloat("19.6"),
"Tax": parseFloat("0.2"),
"Discount": 0.00,
};
salesOrders.push(obj);
salesOrders.push(obj2);
console.log(salesOrders);
$.ajax({
url:"https://localhost:44316/home/CreateOrder",
type:'post',
data:{
SalesOrderDetail: salesOrders
},
success:function(data){
alert(data);
}
});
});
[HttpPost]
public string CreateOrder(List<SalesOrderDetail> SalesOrderDetail)
{
return "success";
}
And Per my test, if you have to use contentType: 'application/json; charset=utf-8',, you can try code below, it also worked:
[HttpPost]
public string CreateOrder([FromBody]List<SalesOrderDetail> salesOrders)
{
return "success";
}
$.ajax({
url:"https://localhost:44316/home/CreateOrder",
contentType: 'application/json; charset=utf-8',
type:'post',
data:JSON.stringify(salesOrders),
success:function(data){
alert(data);
}
});

How do we bind the data in kendo?

function showCopy() {
var arr = [];
var data = $("#PlanDetailGrid").data("kendoGrid").dataSource.data();
for (var i >
= 0; i < data.length; i++) {
if (arr.indexOf(data[i].SessionName) === -1) {
arr.push(data[i].SessionName);
}
}
You can use this syntax
$('#PlanDetailGrid').data('kendoGrid').dataSource.data(result);//result is the data in json format
From the controller you can return the result as Json and bind it direclty using an ajax like
$.ajax({
type: "post",
datatype: "json",
contenttype: "application/json",
url: "/Controller/getResult",
success: function (result) {
if (result.Data.length > 0) {
$('#PlanDetailGrid').data('kendoGrid').dataSource.data(result.Data);
}
else {
$("#PlanDetailGrid").data("kendoGrid").dataSource.data([]);
}
}
});
in Controller
public ActionResult getResult([DataSourceRequest]DataSourceRequest request)
{
//get the result list
DataSourceResult result = lst.ToDataSourceResult(request);//lst is your resultant list
var jsonResult = Json(result, JsonRequestBehavior.AllowGet);
return jsonResult;
}

How to post json object with multiple values to the Controller from Ajax

I have this Ajax post working for a single value but I need it to work with multiple values. What am I missing?
I have already tried to make the public class 'Value' a List AND Guid[]. I have tried to adjust the method parameter to List AND Value[]. Not sure what else to try.
Class:
public class Value
{
public Guid TimeId { get; set; }
}
Method:
public IActionResult ApproveAllTimesheets([FromBody]Value information)
View JS:
function SubAll() {
var selectedValues = $('#timesheet').DataTable().column(0).checkboxes.selected().toArray();
var instructions = {};
for (var TimeId in selectedValues) {
instructions[TimeId] = { TimeId: selectedValues[TimeId] };
}
var inst = JSON.stringify(instructions);
$.ajax({
url: "/Admin/ApproveAllTimesheets",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: inst,
success: function (result) {
alert(result);
},
error: function (xhr, textStatus) {
if (xhr.status == 401) { alert("Session Expired!"); window.location = "/Account"; }
else {
alert('Content load failed!', "info");
}
}
});
};
If I send through this object it works but I need to send through multiple values like my ajax post will do.
var instructions = { TimeId: "13246578-1234-7894-4562-456789123456" };
UPDATE #1
I found a structure that works for me by extending the class, now I just need to figure out how to create the correct object and array combination.
New Classes:
public class ValueContainer
{
public List<Value> MasterIds { get; set; }
}
public class Value
{
public Guid TimeId { get; set; }
}
Method:
public IActionResult ApproveAllTimesheets([FromBody]ValueContainer information)
Structure I need now (this works hard coded):
var jsonObject = {
"MasterIds": [{ TimeId: "13246578-1234-7894-4562-456789123450" }, { TimeId: "13246578-1234-7894-4562-456789123451" }, { TimeId: "13246578-1234-7894-4562-456789123452" }]
};
I'm still new to this stuff but what I see is that jsonObject is an object with a Key 'MasterIds' and the corresponding values are an array of objects with the key 'TimeId'...is this a correct evaluation?...and how to create it in code please?
You neec to create an array of objects and then set it in the container object :
var instructions = []; // an array
for (var i = 0; i < selectedValues.length; i++) {
instructions.push({ TimeId: selectedValues[i] };
}
var Value = {TimeId: instructions}; // creating object with property TimeId as array of guid
var inst = JSON.stringify(Value);
.......
....... your ajax code
and your class property should also be of type array:
public Guid[] TimeId { get; set; }

image browser imageBrowser_listUrl not working

i have tried to get the plugin Image-Browser to work, but i cant figure out, what im missing here.
im using this class:
public class GetImagesToJsonClass
{
public string image { get; set; }
public string thumb { get; set; }
public string folder { get; set; }
}
and this JsonResult
public JsonResult GetFiles()
{
List<GetImagesToJsonClass> GetFiles = new List<GetImagesToJsonClass>();
DirectoryInfo GetDIR = new DirectoryInfo(System.Web.HttpContext.Current.Server.MapPath("~/Content/Images/"));
foreach (FileInfo item in GetDIR.GetFiles())
{
GetImagesToJsonClass NewFile = new GetImagesToJsonClass();
NewFile.image = string.Format("/Content/Images/{0}", item.Name);
NewFile.thumb = string.Format("/Content/Images/{0}", item.Name);
NewFile.folder = "Test";
GetFiles.Add(NewFile);
}
string GetJson = JsonConvert.SerializeObject(GetFiles);
return Json(GetJson, JsonRequestBehavior.AllowGet);
}
using this on a "test" site
<script>
var myURL = '#Url.Action("GetFiles", "Sales")';
var Getfiles = $.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: myURL,
data: "",
datatype: "Json",
});
Getfiles.done(function () {
try {
var tempdata = (Getfiles.responseText);
var data = JSON.parse(tempdata);
document.write(data);
}
catch (e) {
alert("fejl:" + e);
}
});</script>
and the output is:
[{"image":"/Content/Images/testimage2.jpg","thumb":"/Content/Images/testimage2.jpg","folder":"Test"}]
and ofc this to activat it
CKEDITOR.replace('editor1', {
"extraPlugins": 'imagebrowser',
"imageBrowser_listUrl": "/Sales/Test"
});
And get an error
parsererror: invalid JSON file: "/Sales/Test/": Unexpected token <
and if i set the feed directly in i get a [object, object] error?
what am i doing wrong here?

how i could iterate over json array of array

i want to iterate over a json array of arrays from th controller i want to know how i could iterate over it
i need help: nay could help me i'm new to json and mvc
//server code
var jsonData = new
{
rows =
(from bathymetrie in bathymetries
select new
{
count = bathymetries.Count,
Id = bathymetrie.Id,
date = (bathymetrie.displayedDate != null) ?
bathymetrie.displayedDate.ToString() : ""
}).ToArray()
};
//client code
success: function (data) {
bathyms = "{";
for (var i = 0; i < data[1].count; i++) {
bathyms += el[i].Id + " : " + el[i].date;
alert(el[i].Id);
alert(el[i].date);
console.log(el[i].date);
if (i != data[0].count) {
bathyms += ",";
}
}
bathyms += "}";
}
Your data is an object with single field row, which contains an array of objects. Thus, iteration should look like this:
for (var i = 0; i < data.rows.length; i++) {
var element = data.rows[i];
// use element.Id, element.count and element.date
Say if you have your model like this -
public class Data
{
public int Id { get; set; }
public int Count { get; set; }
public string Date { get; set; }
}
And you are returning JsonResult of Array object like this -
public ActionResult GetJson()
{
Data[] a = new Data[2];
a[0] = new Data() { Count = 10, Id = 1, Date = "2/19/2014" };
a[1] = new Data() { Count = 20, Id = 2, Date = "3/19/2014" };
return new JsonResult() { Data = a };
}
Then you can invoke this action in JQuery in the following way -
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
function submitForm() {
jQuery.ajax({
type: "POST",
url: "#Url.Action("GetJson")",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
$.each(data, function (key, value) {
alert(value.Id + ' ' + value.Count + ' ' + value.Date);
});
},
failure: function (errMsg) {
alert(errMsg);
}
});
}
</script>
<input type="button" value="Click" onclick="submitForm()" />
Please observe following code which will iterate array -
success: function (data) {
$.each(data, function (key, value) {
alert(value.Id + ' ' + value.Count + ' ' + value.Date);
});
Output would be N number of alerts based on N elements in array like below -

Resources