I am trying to post a complex object which classes are defined at ASP.NET.
It is an array of "Site" which contains an array of "Variable" which contains an array of "Source".
It works perfectly if third level array (Sources) has 1 elem or less. Otherwise, it fails. (action controller is not called) Why?
It works perfectly with MVC 3. It fails with MVC 4. Why?
Ajax post call:
$.ajax({
type: 'POST',
url: 'FieldData/GetStiffKml',
data: JSON.stringify({ sitesForStiff: sites }),
datatype: "json",
contentType: "application/json; charset=utf-8",
success: function (data) { }
});
Action method:
public ContentResult GetStiffKml(Site [] sitesForStiff){
...
}
Class structure:
public class Site
{
public string SiteCode { get; set; }
public List<Variable> Variables { get; set; }
}
public class Variable
{
public int VariableID { get; set; }
public List<Source> Sources { get; set; }
}
public class Source
{
public int SourceID { get; set; }
public int ValueCount { get; set; }
}
Related
I have a viewModel
public class School
{
public int SchoolId { get; set; }
public int BuildingId { get; set; }
public int FloorId { get; set; }
public int PlannedBy { get; set; }
public IEnumerable<HeadCountPerRoom> HeadCountPerRoom{ get; set; }
}
And my controller looks like this:
public JsonResult SaveHeadCount(IEnumerable<School>schoolViewModel,int action)
{
// my code
}
I have written the javascript model and ajax:
function myfuncton() {
var HeadCountPerRoom=[];
var MasterEntry=[];
HeadCountPerRoom.push({
Month: month,
Year: year,
HeadCountId: seatCountID,
SeatCount: SeatCount,
});
masterEntry= JSON.stringify({
schoolViewModel:{
SchoolId: SchoolId,
BuildingId: BuildingId,
FloorId: FloorId,
PlannedBy: PlannedBy,
HeadCountPerRoom: HeadCountPerRoom
},
action:3
});
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: "../myController/SaveHeadCount",
data: masterEntry,
success: function (data) {
//code.
}
})
In the controller I am getting null in the schoolViewModel parameter and for the action parameter I am getting the value. Why I am getting null?
You are expecting a list of school and you your JS you're passing only ONE object. You should pass your model on your JS as an array:
schoolViewModel: [
{
SchoolId: SchoolId,
BuildingId: BuildingId,
FloorId: FloorId,
PlannedBy: PlannedBy,
HeadCountPerRoom: HeadCountPerRoom
}
]
I have this JQuery function:
function EditContactPost()
{
var urlEditPost = $("#hdnInfo").data("url_add_contact");
var test = $("#formEditContact").serialize();
alert(test);
$.ajax({
type: 'post',
url: urlEditPost,
data:{ marketingContactVM: test },
})
}
I'm doing an alert as you see and I'm watching that the test variable has the form serialized correctly with all the values. But when the controller action receives this request on server side marketingContactVM is always null. Why is this happening?
My controller action looks like this:
[HttpPost]
public ActionResult AddContact(MarketingVM marketingContactVM) //always null
{
some code...
}
Just in case this is my model class, it contains another list inside:
public class MarketingVM
{
public IEnumerable<string> States { get; set; }
public List<MarketingVM> MarketingList { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public string Company { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
public string Country { get; set; }
public string Phone { get; set; }
public string Fax { get; set; }
public string Mail{ get; set; }
public string URL { get; set; }
public bool IsTrue{ get; set; }
public int OtherId{ get; set; }
}
I've checked the Network tab in DevTools and this is the Request URL:http://localhost:56602/ControllerName/AddContact , that should be fine.
But the data is being sent as a FormData, like this:
marketingContactVM:Company=Microsoft+Company&Email=user10%40email.co&First=
Auto&Last=Mapper&Phone=98797988997&Fax=&URL=ww.auto.org&Adress=automapper+
street&City=auto+city&State=FL&Zip=33654&Country=USA&MarketingContacts%5B0%5D
.Name=1%2F03%2F2012+1%3A15+PM&MarketingContacts%5B0%5D.IsSelected=false
.. and like that. Maybe the way the data is being sent.. I think that the correct format should be:
marketingContactVM:
Company=Microsoft Company Email=user10#email.co First=Charles Last=Johnston Phone=98797988997 Fax=989898 URL=ww.auto.org Adress=North streetCity=Sacramento State=FL Zip=33654 Country=USA MarketingContacts.Name=Piotr
MarketingContacts.IsSelected=false
since you are serializing the form you dont need to add it in json object
data:{ marketingContactVM: test },
instead just pass the serialized object like this
$.ajax({
type: 'post',
url: urlEditPost,
data:test,
})
Try this:
$.ajax({
url: urlEditPost,
method: "POST",
data: { marketingContactVM: test },
dataType: "json"
});
Add the contentType property. This way AP.NET MVC will know to deserialize the request body as JSON.
function EditContactPost()
{
var urlEditPost = $("#hdnInfo").data("url_add_contact");
var test = $("#formEditContact").serialize();
alert(test);
$.ajax({
type: 'post',
url: urlEditPost,
data:{ marketingContactVM: test },
contentType: 'application/json'
})
}
PS: Also you should use data: JSON.stringify(test).
I can't seem to figure out how to get my Javascript object to bind to my model that is (as far as I can tell) just like it as far as properties go.
First the Javascript Object creation:
var transDetail = new Object();
transDetail.TransactionDetailID = transdetailId;
transDetail.TransactionID = "";
transDetail.Year = new Date().getFullYear();
transDetail.Volume = "";
transDetail.UnitPrice = "";
transDetail.TransferableVolume = "";
transDetail.Credits = "";
transDetail.Shares = "";
transDetail.DollarsPerShare = "";
It is then passed to this javascript function
function loadTransDetailEditCreate(d, cb, title, transactionDetail) {
$.ajax(
{
url: '/TransactionDetail/LoadEditCreate',
data: JSON.stringify(transactionDetail),
dataType: 'json',
success: function (result) {
d.html(result);
CreateEditTransDetail(d, cb, title, transactionDetail);
d.dialog('open');
}
}
);
}
I've verified that the year property before transmission is filled with 2015.
Now the model definition
public partial class TransactionDetail
{
public int TransactionDetailID { get; set; }
public int TransactionID { get; set; }
public int Year { get; set; }
public Nullable<int> Volume { get; set; }
public Nullable<int> UnitPrice { get; set; }
public Nullable<int> TransferableVolume { get; set; }
public Nullable<int> Credits { get; set; }
public Nullable<int> Shares { get; set; }
public Nullable<int> DollarsPerShare { get; set; }
}
And the Action definition
public PartialViewResult LoadEditCreate(TransactionDetail transactionDetail)
When I break first thing into the action all non nullable ints are set to 0 and all nullable are set to null.
The problem is with sending the data: JSON...
You have 2 options:
use POST: (tried and works)
function loadTransDetailEditCreate(d, cb, title, transactionDetail) {
$.ajax(
{
type: 'post', //added
contentType: "application/json; charset=utf-8", //added
url: '/TransactionDetail/LoadEditCreate',
data: JSON.stringify(transactionDetail),
dataType: 'json',
success: function (result) {
d.html(result);
CreateEditTransDetail(d, cb, title, transactionDetail);
d.dialog('open');
}
}
);
}
and decorate your controller with [HttpPost] attribute
[HttpPost]
public PartialViewResult LoadEditCreate(TransactionDetail transactionDetail)
If you want to use get - look here (didn't try, should work)
I have tried many different solutions from other people but have had no luck with either, and I can't seem to be able to debug javascript.
These are some of the variables just so you can see the types. All variables contain data
My view is as follows:
var startTime = new Date();
var images = #Html.Raw(Json.Encode(ViewBag.Images));
var sound = #Html.Raw(Json.Encode(ViewBag.Tones));
var gamePlayed = #Html.Raw(Json.Encode(ViewBag.GamePlayedId));
function SaveGameData()
{
$.ajax({
type: 'POST',
url: '#Url.Action("Play", "Game")',
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: {
GamePlayedId: gamePlayed,
Level: level,
ExpectedImageName: expectedImageArray,
ExpectedToneName: expectedToneArray,
SelectedImageName: selectedImageArray,
SelectedToneName:selectedToneArray,
StartTime: startTimeArray,
EndTime: endTimeArray
},
success: function () {
alert('suc');
},
error: function (args) {
alert('error');
}
});
}
My controller is as follows:
[Authorize]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Play(SaveGameViewModel model)
{
// Do something
return Json(new { success = true , message ="successful"});
}
My viewmodel is as follows:
public class SaveGameViewModel
{
public int GamePlayedId { get; set; }
public int Level { get; set; }
public List<string> ExpectedImageName { get; set; }
public List<string> ExpectedToneName { get; set; }
public List<string> SelectedImageName { get; set; }
public List<string> SelectedToneName { get; set; }
public List<DateTime> StartTime { get; set; }
public List<DateTime?> EndTime { get; set; }
}
I keep getting the error message from the ajax alert. I have tried many different things and nothing seems to work. I appreciate any help that you can give. Thanks a lot!
There are at least 2 issues with the code your have shown.
First your method is marked with the [ValidateAntiForgeryToken] attribute but you do not pass the token so the method will never be run. Either remove the attribute, or include it using (this assumes your form includes #Html.AntiForgeryToken())
data: {
__RequestVerificationToken: $('[name=__RequestVerificationToken]').val(),
.... // your other properties
},
Second, your posting a javascript object so you need to remove the contentType: "application/json; charset=utf-8", option (or alternatively you need to stringify the data using JSON.stringify()
Side note: Its unclear from you code why you are manually constructing an object to send to the controller. If your form controls are based on SaveGameViewModel and are correctly generated using the strongly typed html helpers, then you can post it all back using
$.ajax({
data: $('form').serialize(),
....
});
Until now, I've been successfully passing an array of strings to my controller via AJAX using JSON.stringify.
However, now I need to move that array into another object in order to pass more data to the AJAX call.
The following (and many other attempts) result in the jobRequest.Tests having no members when passed to the controller:
function executeTests(testsToRun) {
if (testsToRun.length > 0) {
var jobRequest = new Object;
jobRequest.SampleTitle = '#ViewBag.SampleTitle';
jobRequest.SampleLanguage = '#ViewBag.SampleLanguage';
jobRequest.Mode = '#ViewBag.SampleMode';
jobRequest.Tests = JSON.stringify(testsToRun);
$.ajax({
url: '#Url.Action("ProcessJob", "ProcessJob")',
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ 'jobRequest': jobRequest }),
success: function (jobId) {
window.location.href = '#Url.Action("Index", "ProcessJob")' + '?id=' + jobId;
}
});
}
}
public class JobRequest
{
public string SampleTitle { get; set; }
public string SampleLanguage { get; set; }
public string Mode { get; set; }
public List<string> Tests = new List<string>();
}
public JsonResult ProcessJob(JobRequest jobRequest)
{
...
You can change the class JobRequest like this:
public class JobRequest
{
public string SampleTitle { get; set; }
public string SampleLanguage { get; set; }
public string Mode { get; set; }
public List<string> Tests { get; set; }
}
and remove the JSON.stringify in the array:
jobRequest.Tests = testsToRun;