How to post json object with multiple values to the Controller from Ajax - asp.net-mvc

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

Related

Why this ajax post request does not work in mvc app

i have js file with ajax request
this is part of its text
$.ajax({
url: '/Points/Addpoint', // также '#Url.Action("Addpoint", "PointsController")'
type: "POST",
dataType: "json",
data: JSON.stringify({ firstx: ev._x, firsty: ev._y, secondx: ev._x, secondy: ev._y }),
success: function () {
alert();
}
});
i also have mvc controller with this method which should be called in ajax
[HttpPost]
public void Addpoint(JSON po)
{
var pointslist = this.Getpoints();
var obj = po;
pointslist.Add(new Point());
}
But somehow this doesnt work. idk why?it gives me 500 error and message
There are no parameterless constructors defined for this object.
what should i do to solve this problem and send this json obj?
Change the JSON to class and change your post
public class YourClass
{
public string firstx { get; set; }
public string firsty { get; set; }
public string secondx { get; set; }
public string secondy { get; set; }
}
[HttpPost]
public void Addpoint([FromBody] YourClass po)
{
var pointslist = this.Getpoints();
var obj = po;
pointslist.Add(new Point());
}
$.ajax({
url: '/Points/Addpoint',
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({ firstx: ev._x, firsty: ev._y, secondx:ev._x,secondy: ev._y }),
success: function () {
}
});

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?

Json to List<object> not binding

I have a problem with object send in json format, that is not binded in Action Controller
Here the json parts:
function filterTxAjustement(arrTx) {
return {
dateDebut: $("#TxAjustementDateDebut").val(),
dateFin: $("#TxAjustementDateFin").val(),
ufCode: $("#TxAjustementUf").val(),
tx: JSON.stringify(arrTx)
};
}
function SaveTx() {
var arrTx = [];
$.each(Day, function (i, v) {
var $this = $('#' + v + 'Tx');
var tx = new Object();
tx.Day = v;
tx.Nb = parseInt($this.val());
tx.UfCode = parseInt($('#TxAjustementUf').val());
tx.Total = 0;
arrTx.push(tx);
});
$.ajax({
url: EasilyRelativeUrl("Lit/SetTxAjustementByDateAndUf"),
data: filterTxAjustement(arrTx),
type: 'POST',
dataType: 'json'
}).done(function (data) {
$('#TxAjustementGrid').data("kendoGrid").dataSource.read();
});
}
My array is well populated:
dateDebut:16/12/2013
dateFin:22/12/2013
ufCode:21124
tx:[{"Day":"Sunday","Nb":1,"UfCode":21124,"Total":0},{"Day":"Monday","Nb":2,"UfCode":21124,"Total":0},{"Day":"Tuesday","Nb":3,"UfCode":21124,"Total":0},{"Day":"Wednesday","Nb":0,"UfCode":21124,"Total":0},{"Day":"Thursday","Nb":0,"UfCode":21124,"Total":0},{"Day":"Friday","Nb":0,"UfCode":21124,"Total":0},{"Day":"Saturday","Nb":0,"UfCode":21124,"Total":0}]
But when it hit Action Controller, tx is null
public ActionResult SetTxAjustementByDateAndUf(DateTime dateDebut, DateTime dateFin, string ufCode, List<TauxAjustement> tx)
(Here the TauxAjustement object)
public class TauxAjustement
{
public string Day { get; set; }
public int Nb { get; set; }
public int Total { get; set; }
public int UfCode { get; set; }
}
I have tried with TauxAjustement[], but same issue. I have added Total = 0 and parseInt to have exact definition of C# object, but same...
What have I missed ? I do make a CustomBinderModel for this ?
Thanks for your help.
You need to define the tx argument as an array rather than a List:
public ActionResult SetTxAjustementByDateAndUf(DateTime dateDebut,
DateTime dateFin,
string ufCode,
TauxAjustement[] tx)
{}

Jquery post to mvc 4 controller not passing data

I'm trying to pass data from JQuery to an MVC 4 controller. The controller gets invoked, but no data is passed. In the past I always just used form serialization, but that's not appropriate here.
My Controller:
[HttpPost]
public ActionResult Write(VideoSessionEnvelope envelope)
{
if (ModelState.IsValid)
{
envelope = Log.Write(envelope);
}
var result = Json(envelope);
return result;
}
We use an envelope class as a container for all view models
public class VideoSessionEnvelope : BaseEnvelope
{
public VideoSessionEnvelope()
{
SessionStart = new VideoSessionStartViewModel();
}
public Guid? LogEntryID { get; set; }
public VideoSessionStartViewModel SessionStart { get; set; }
}
}
The view model
public class VideoSessionStartViewModel: IViewModel
{
public string SessionId { get; set; }
public int UserId { get; set; }
public string Message { get; set; }
}
And finally the javascript
var Logging = Logging || {};
Logging.VideoSession = function () {
var Start = function (sessionId, userId, message) {
var envelope = {
SessionStart: {
"SessionId": sessionId,
"UserId": userId,
"Message": message
}
}
var data = JSON.stringify(envelope);
$.ajax({
type: "POST",
url: "/Logging/Write",
data: data,
datatype: "application/json",
success: function (result) {
return result;
},
error: function (request, status, error) {
return error;
}
});
};
return {
Start: Start
};
}();
According to Firebug the data is passed as
JSON
SessionStart Object { SessionId="sessionIdVal", UserId=123, Message="messageValue"}
Message "messageValue"
SessionId "sessionIdVal"
UserId 123
The controller gets called, but the properties in the view model are always null. I've tried several variations on the theme, nothing seems to work.
Try wrapping your data in a literal with the name as envelope so it will be picked up by the Model Binder:
data: { envelope: data },
UPDATE
Remove the call to JSON.stringify(), it is not strictly necessary to serialize the object literal.

Want to Save Posted Json data to database

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.

Resources