Javascript send list to asmx service - javascript

I create an asmx service in .net web forms as below. The AddUsers method accept List model.
namespace ProjectName.AsmxServices.Test
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[ScriptService]
public class Test: System.Web.Services.WebService
{
[WebMethod]
public void AddUsers(List<UserDetail> userList)
{
// Add User List
}
// Here is my model
public class UserDetail
{
public int Id{ get; set; }
public string Name { get; set; }
public string Surname{ get; set; }
public DateTime BirthDate { get; set; }
}
}
}
Now, I want to post List model in Javascript. But how can I create this model as list in javascript ?
$("#addUsers").click(function () {
var data = ?? **How can I create a List<UserDetail> model.**
$.ajax({
url: '../AsmxServices/Test.asmx/AddUsers',
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: data
success: function (result) {
console.log("Good job!");
},
error: function (result) {
console.log("Failed");
}
});
});
I want to create this modelList hardcoded now. Then I will change my code.

Try this:
var usersList =
{
userList:
[
{Id: 1, Name: "name1"},
{Id: 2, Name: "name2"}
]
};
var data = JSON.stringify(usersList);

Related

Javascript : Pass complex object to my controlleur (asp core)

Trying to send object to my controller :
$.ajax({
type: "POST",
url: '/Groups/Invite',
contentType: "application/json",
data: JSON.stringify(UserInvited),
dataType: "json",
success: function () {},
error: function (xhr, status, error) {}
});
In debug mode, my data is :
{"Id":"47","Guest":[{"Key":"","Pseudo":"Lolo01500","Del":false,"Add":true}]}
My Action in controller :
[HttpPost, ActionName("Invite")]
public IActionResult Invite(GroupInviteVM groupInviteVM)
{
// TODO
return Json(true);
}
And Targets object classes :
public class ItemInvite
{
public string Key { get; set; }
public string Pseudo { get; set; }
public bool Add { get; set; }
public bool Del { get; set; }
}
public class GroupInviteVM
{
public int Id { get; set; }
List<ItemInvite> Guest { get; set; }
public GroupInviteVM()
{
Guest = new List<ItemInvite>();
}
}
When execute, only the Id is updated ...
Somebody could help me ?
T.Y.
When execute, only the Id is updated ...
That is because the Guest property is not public.Add public modifier like below:
public class GroupInviteVM
{
public int Id { get; set; }
public List<ItemInvite> Guest { get; set; }//change this
public GroupInviteVM()
{
Guest = new List<ItemInvite>();
}
}
The whole demo:
View:
<script>
var UserInvited = {
Id: 1,
Guest: [{
Key: "aaa",
Pseudo: "asd"
}]
};
console.log(JSON.stringify(UserInvited));
$.ajax({
type: "POST",
url: '/Groups/Invite',
contentType: "application/json",
data: JSON.stringify(UserInvited),
dataType: "json",
success: function () { },
error: function (xhr, status, error) { }
});
</script>
Controller:
[HttpPost, ActionName("Invite")]
public IActionResult Invite([FromBody]GroupInviteVM groupInviteVM)
{
// TODO
return Json(true);
}

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'

Passing Multiple JSON objects via AJAX to ASP.Net PageMethod

I am trying to pass two JSON Objects to my Page Method via AJAX
I created a class in Code Behind and created a JSON Object Array in javascript.
Following are my two classes and Page Method
public class userModel
{
public string userid { get; set; }
public string Name { get; set; }
}
public class companyModel
{
public string companyid { get; set; }
public string Name { get; set; }
}
[WebMethod]
public static string TestJsonMethod(userModel[] users)
{
return "";
}
And Following is my Javascript
function TestJSON() {
//var JSONObject = { a: [], b };
var obj = {users: []};
var user;
for (var i = 0; i < 3; i++) {
user = {
userid: i.toString(),
Name: "User" + i.toString()
}
obj.users.push(user);
}
var company = {companyid: "4", Name:"TEST COMPANY"};
$.ajax({
url: "bulkconsignments.aspx/TestJsonMethod",
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(obj),
async: false,
cache: false,
success: function (msg) {
alert(msg.d);
}
});
}
Up till this point my code is working fine.
What I want to do is to pass the company object to the Page Method as well like this
[WebMethod]
public static string TestJsonMethod(userModel[] users, companyModel company)
{
return "";
}
You could merge the models into one model.
public class TestJsonModel
{
public UserModel UserModel { get; set; }
public CompanyModel CompanyModel { get; set; }
}
Then action looks like;
[WebMethod]
public static string TestJsonMethod(TestJsonModel model)
Also, Ajax request post data looks like;
data: JSON.stringify({UserModel:obj,CompanyModel:company})
I was trying out different ways of doing it and this one worked.
function TestJSON() {
//var JSONObject = { a: [], b };
var obj = {users: [], company: {}};
var user;
for (var i = 0; i < 3; i++) {
user = {
userid: i.toString(),
Name: "User" + i.toString()
}
obj.users.push(user);
}
var company_ = {companyid: "4", Name:"TEST COMPANY"};
obj.company = company_;
$.ajax({
url: "bulkconsignments.aspx/TestJsonMethod",
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(obj),
async: false,
cache: false,
success: function (msg) {
alert(msg.d);
}
});
}
And the Code behind Page Method remains same.
[WebMethod]
public static string TestJsonMethod(userModel[] users, companyModel company)
{
return "";
}

Passing data from Ajax to controller in asp.net mvc

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

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

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;

Categories