Passing an array as part of an object to an Ajax call - javascript

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;

Related

js post complex object to asp.net mvc

The data format in js is like:
var data = {};
data = {
orderInfo: {
time: '2018-04-01',
phone: '111122223333'
},
products: [
{id: 1, count: 1},
{id: 2, count: 2}
]
}
however when I post it directly using jQuery's ajax() method, the back end cant receive what I posted, But when posted in the format like:
var data = {};
data['orderInfo.time'] = '2018-04-01';
data['orderInfo.phone'] = 111122223333;
data['products[0].id'] = 1;
data['products[0].count'] = 1;
data['products[1].id'] = 2;
data['products[1].count'] = 2;
the data can be received by back end, what caused this? Any help will be thankful.
ajax code:
$.ajax({
type: 'POST',
data: data,
url: '/SaveOrderInfo'
}).done(function (data, status, request) {
}).fail(function (err) {
});
simplified back end code
namespace balabala {
[DataContract]
public class RVOrderViewRqst : IExtensibleDataObject
{
public ExtensionDataObject ExtensionData { get; set; }
[DataMember]
public RVOrderCustom orderInfo { get; set; }
[DataMember]
public IList < RVOrderDetailCustom > products { get; set; }
public RVOrderViewRqst()
{
products = new List<RVOrderDetailCustom>();
}
}
[DataContract]
public class OrderDetailInfoCustom {
[DataMember]
public RVOrderCustom orderInfo { get; set; }
[DataMember]
public IList < RVOrderDetailCustom > products { get; set; }
public OrderDetailInfoCustom()
{
products = new List<RVOrderDetailCustom>();
}
}
[DataContract]
public class RVOrderDetailCustom {
[DataMember]
public int id { get; set; }
[DataMember]
public int count { get; set; }
}
[DataContract]
public class RVOrderCustom {
[DataMember]
[DataMember]
public string time { get; set; }
[DataMember]
public string phone { get; set; }
}
}
It's to complicated for me to understand, and the back end dude cant find the reason.
Try to add dataType: 'json'
$.ajax({
type: 'POST',
data: data,
url: '/SaveOrderInfo',
dataType: 'json'
}).done(function (data, status, request) {
}).fail(function (err) {
});
And you also need to set in BE the header like
Response.ContentType = "application/json";
Or
Response.Headers.Add("Content-type", "application/json");
Try to add dataType option to ajax call.
dataType: 'json'

ASP Net Core MVC Ajax Post

I have the following code and it works perfectly fine until I add the last property in the js object
JS:
var serializableFilter = {};
serializableFilter.aosType = filter.aos.type;
serializableFilter.aosText = filter.aos.text;
serializableFilter.industries = filter.industries.getCommaSeperatedIDs();
serializableFilter.servicingBanks = filter.servicingBanks.getCommaSeperatedIDs();
serializableFilter.category = filter.categories.categoryID;
serializableFilter.yearEstablishedFrom = filter.yearEstablished.from;
serializableFilter.yearEstablishedTo = filter.yearEstablished.to;
serializableFilter.staffMin = filter.nbStaff.min;
serializableFilter.staffMax = filter.nbStaff.max;
//serializableFilter.includeBranches = filter.includeBranches;
$.ajax({
url: url,
type: "POST",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(serializableFilter),
success: function (result) {
console.log(result);
},
error: function () {
alert('error');
}
});
C#:
[HttpPost]
public async Task<IEnumerable<FdxxxMap>> GetC([FromBody] Filter data)
Model:
public class Filter
{
public string aosType { get; set; }
public string aosText { get; set; }
public string industries { get; set; }
public string servicingBanks { get; set; }
public int category { get; set; }
public int yearEstablishedFrom { get; set; }
public int yearEstablishedTo { get; set; }
public int staffMin { get; set; }
public int staffMax { get; set; }
public Boolean includeBranches { get; set; }
}
Whenever I add the last property of type boolean, the data model is passed as null
I wonder if the type of filter.includeBranches is really bool.
Why wouldn't you try this:
serializableFilter.includeBranches = filter.includeBranches==true;

Ajax Post request MVC

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).

Can't get Javascript Object to bind to a action Controller

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)

how to pass $("form").serialize() with array list from AJAX method to mvc controller?

I have to pass model and also another array list value from javascript to controller.
Javascript code
$("#SaveData").click(function (e) {
debugger
var formdata = $("form").serialize();
var list = new Array();
var postData;
$('input.chkevent').each(function () {
debugger
if (this.checked == true) {
var parent_id = this.parentElement;
var par2 = parent_id.previousElementSibling;
var par3 = par2.previousElementSibling;
var child = par3.childNodes[0];
var child_val = child.defaultValue;
var arr_date = this.parentElement.nextElementSibling.childNodes[0].value;
var dep_date = this.parentElement.nextElementSibling.nextElementSibling.childNodes[0].value;
var id = new Array(); ;
id.push(child_val, arr_date, dep_date);
list.push(id);
postData = {values: list };
}
});
$.ajax({
type: "POST",
url: "/umbraco/Surface/HomeSurface/FormData",
data: (formdata ? formdata + "&" : "") + "values=" + postData,
traditional: true,
success: function (data) {
//alert("ajax request to server succeed");
}
});
});
Only one kind of data I got, either postDataor formdata but I need both of them to pass in controller method as below:
public ActionResult FormData(PERSON_MASTER person, string[] values)
{}
PERSON_MASTER.cs
public class PERSON_MASTER
{
[Key]
public int PERSON_ID { get; set; }
public string ICARD_ID { get; set; }
[Required]
public string FNAME { get; set; }
[Required]
public string LNAME { get; set; }
public string GENDER { get; set; }
[DataType(DataType.Date)]
public DateTime DOB { get; set; }
[Required]
public int? CITY_ID { get; set; }
public int? STATE_ID { get; set; }
[Required]
public int? COUNTRY_ID { get; set; }
public string CONTACT_NO { get; set; }
}
Thanks in advance.
Try this, not tested:
var model = {
person: $("form").serialize(),
values: list
};
$.ajax({
type: "POST",
url: "/umbraco/Surface/HomeSurface/FormData",
data: JSON.stringify(model),
traditional: true,
success: function (data) {
//alert("ajax request to server succeed");
}
});
Whenever i pass data to controller, i make sure that the parameter names coresponds with the parameter names in the controller:
$.ajax({
type: "POST",
url: "/umbraco/Surface/HomeSurface/FormData",
data: {
person: formdata,
values: list
},
traditional: true
});
Update: You must also make sure that the parameters has the same shape. In your code you are passing a multidimensional array to non-multidimensional array

Categories