AngularJs Post Object with child collections to a MVC WebAPI - javascript

I am working on an AngularJS App, and one of the methods in the service js post data to a web api with a following object structure in C#
public class InvitationModel
{
public string Name { get; set; }
public string Email { get; set; }
public EventModel[] EventList { get; set; }
}
public class EventModel
{
public string EventName { get; set; }
public int TotalAdults { get; set; }
public int TotalChildren { get; set; }
public bool IsAccepted { get; set; }
}
Problem is that when I post this data to a WEBAPI method, my parent level properties serializes correctly except the one that holds the collection. It gets set to null always.
The web API method that recieves the request is :
[AllowAnonymous]
[Route("RSVP")]
[HttpPost]
public bool Submit(InvitationModel invitationModel)
{
return true;
}
So, Name and Email serialize correctly, but EventList is NULL
I did check on the javascript side, and my js object holds both the array and other primitive properties. Issue I guess is at the .NET WebAPI side.
Request payload that gets posted is something like this :
{ "Name":"John Doe",
"EventList":{
"0":{ "TotalAdults":"1",
"TotalChildren":"2",
"EventName":"Event 1 Name"
},
"1":{ "TotalChildren":"2",
"TotalAdults":"2",
"EventName":"Event 2 Name"
},
"2":{ "TotalAdults":"1",
"TotalChildren":"1",
"EventName":"Event 3 Name"
}
}
}

The EventList in your JSON is an object with properties "0", "1", etc.
I guess it should be a JSON array, i.e.
{
"Name":"John Doe",
"EventList": [
{"TotalAdults":"1","TotalChildren":"2","EventName":"Event 1 Name"},
{"TotalChildren":"2","TotalAdults":"2","EventName":"Event 2 Name"},
...
], ...
to be correctly read into your C# eventlist property.

Related

Array inside JSON received empty

I'm sending a JSON object when submitting a form that contains some primitive types and one array of objects from a browser (JavaScript) to an ASP.NET MVC backend, but the array of objects is deserialized as an empty array (list, actually).
I've checked what's being sent using Chrome's inspector and the JSON goes out with the correct values, so I believe the issue is in the backend.
Controller action:
[HttpPost]
public ActionResult FooAction(FooViewModel viewModel)
{
//code
}
FooViewModel:
public class FooViewModel
{
public List<BarViewModel> Bars { get; set; } // <-- What arrives empty, not null
public int PrimitiveProperty { get; set; }
public int OtherPrimitiveProperty { get; set; }
public string LastPrimitiveProperty { get; set; }
}
BarViewModel:
public class BarViewModel
{
public long LongProperty{ get; set; }
public string StringProperty { get; set; }
public bool BoolProperty { get; set; }
}
When debugging the controller's action, Bars is empty (not null).
And this is what Chrome's inspector shows me:
LastPrimitiveProperty: SomeText
PrimitiveProperty: 1
OtherPrimitiveProperty: 9
Bars: [{"LongProperty":274,"StringProperty":"SomeString","BoolProperty":true},{"LongProperty":119,"StringProperty":"SomeString","BoolProperty":false},{"LongProperty":163,"StringProperty":"SomeString","BoolProperty":false}]
[HttpPost]
public ActionResult FooAction([FromBody]FooViewModel viewModel)
{
//code
}
Try this and it should collect the json object

How to JSON Data Format JavaScript Serializer in ASP.NET

I am writing an ASP.NET web service. I made the connection to SQL Server. The web service is using a JavaScript serializer. My JSON format:
[{"ID":1,"TCKN":"19","Adi":"zzz","Soyadi":"aa"},
{"ID":2,"TCKN":"99","Adi":"user","Soyadi":"user"}]
But I want this JSON format:
"users": [
{
"ID": "1",
"TCKN": "19",
"Adi": "zzz",
"Soyadi": "aa"
},
{
"ID": "2",
"TCKN": "99",
"Adi": "user",
"Soyadi": "user"
},]
WebServices.cs
[WebMethod]
public string getTumKullanici()
{
JavaScriptSerializer jss = new JavaScriptSerializer();
var json = "";
var tumKullanicilar = from result in mydb.Kullanicilars
select result;
json = jss.Serialize(tumKullanicilar);
return json;
}
My understanding is that the way the JSON is displayed lacks of new line chars etc - that's completely normal and desired, as extra characters are useless for services. To make the JSON more readable to humans, you could use tools that enable formatting, as f.e. addon to Notepad++ or some webapp. But for general use as data in computing I would stick to raw format without the tabulators and new lines.
Whenever you're dealing with JSON data that you need to serialize into C#, go to Json2CSharp
Using that site I've got your C# data model:
public class RootObject
{
public int ID { get; set; }
public string TCKN { get; set; }
public string Adi { get; set; }
public string Soyadi { get; set; }
}
Next you're going to need JSON.NET
You can get that by opening the nuget package manager and searching Newtonsoft.Json
Or use the Package manager console
PM> Install-Package Newtonsoft.Json
Next you're going to need to deserialize that JSON..
string json = #"{""ID"":1,""TCKN"":""19"",""Adi"":""zzz"",""Soyadi"":""aa""},{""ID"":2,""TCKN"":""99"",""Adi"":""user"",""Soyadi"":""user""}]";
RootObject root = JsonConvert.DeserializeObject<RootObject>(json);
And if you never need to serialize the C# object back into JSON... You can do this.
string backToJson = JsonConvert.SerializeObject(root);
EDIT
You can achieve nesting the under users by wrapping your original object with another class:
public class Users
{
public int ID { get; set; }
public string TCKN { get; set; }
public string Adi { get; set; }
public string Soyadi { get; set; }
}
public class Root
{
public List<User> Users {get;set;}
}
var root = new Root { Users = mydb.Kullanicilars.ToList() };
JsonConvert.SerializeObject(root);

Passing complex object to WebAPI from AngularJS

I am trying to post a JavaScript item to a C# WebAPI call using AngularJS. Below is what I am trying to do.
Objects
class Address
{
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
}
class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Address address { get; set; }
}
My C# Controller function
[Route("Update/")]
public void Update(Person person)
{
_service.Update(person);
}
AngularJS call
this.update = function (person) {
$http.post("api/Person/Update/", person);
}
When I receive the object in the WebAPI controller the address is null. Why is this data not being received?
Edit
I was wrong in my original question the Person object looked like this
class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public IAddress address { get; set; }
}
When I changed address from IAddress to Address everything worked as expected.
Your post would be in json format which will assign person object to person, Address object must be well formed object as it contain sub properties.
Code
$scope.person = {
'Street': '',
'LastName': '',
'Address': {
'Street': '',
'City': '',
'State': '',
},
}
this.update = function (person) {
$http.post("api/Person/Update/", { person : $scope.person});
}
This approach allows to send complex objects with arrays and sub objects through HTTP GET:
Angular:
$http({
url: '/myApiUrl',
method: 'GET',
params: { personStr: angular.toJson(person, false) }
})
C#:
[HttpGet]
public string Get(string personStr)
{
Person obj = new JavaScriptSerializer().Deserialize<Person>(personStr);
...
}
What you want to do is not possible, but this solution allows you to use your complex object on the .NET side. There is no body in a GET request, so you have to add your object into the URI.
Change your web api method to:
[Route("Update/")]
public void Update([FromUri]Person person)
{
_service.Update(person);
}
Change your angular code to:
this.update = function (person) {
$http.post("api/Person/Update?FirstName=John&LastName=Doe&Address%5BStreet%5D=123%20Main%20St&Address%5BCity%5D=Knoxville&Address%5BState%5D=Tennessee");
}

Sending a dictionary of javascript parameters to MVC Controller via JSON

I'm using a third party library and cant really change the way it posts data to my MVC 5 controller.
I cant figure out how to setup my model to receive the data.
The json is a follows...
{
"expiration":"2015-06-14T21:02:52.969Z",
"conditions":[
{"acl":"private"},
{"bucket":"anyoldbucket"},
{"Content-Type":"application/pdf"},
{"success_action_status":"200"},
{"key":"somekey"}
]
}
I tried setting up my model like this...
public class AwsSignatureRequestViewModel
{
public DateTime expiration { get; set; }
public Dictionary<string, string> conditions { get; set; }
}
The expiration date is correctly filled out, and I get the right number of conditions but the keys to the dictionary are numbers (indexes) and the values are null
Any suggestions?
If your model is strict, you will need to make objects for every sub objects.
But if you have a dynamic model, you can read the raw string from your request and parse it with Json.net.
public ActionResult Test(string model)
{
Request.InputStream.Seek(0, SeekOrigin.Begin);
string jsonData = new StreamReader(Request.InputStream).ReadToEnd();
var dynamicObject = JObject.Parse(jsonData);
...
}
dynamicObject will contains all of your json.
IINM, based on the data you're getting, your AwsSignatureRequestViewModel should look something like this:
public class AwsSignatureRequestViewModel
{
public DateTime expiration { get; set; }
public List<Dictionary<string, string>> conditions { get; set; }
}
conditions is an "array of objects".
The way you currently have your model, data would map to something like this (which isn't the case):
{
"expiration": "2015-06-14T21:02:52.969Z",
"conditions":
{
"acl": "private",
"bucket": "anyoldbucket",
....
},
.....
Hth...

ASP.NET Web API - pass a complex type from javascript json

I have an ASP.NET Web API that accepts a POST with a UserModel in it:
[HttpPost]
public object Post(UserModel userModel)
{
// some logic here
}
The UserModel is a complex type that looks like this:
public class UserModel
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public AddressModel CurrentAddress { get; set; }
}
The AddressModel Model looks like this:
public class AddressModel
{
public string Country { get; set; }
public string City { get; set; }
public string Street { get; set; }
public string Number { get; set; }
}
I'm trying to call this API from javascript and send a JSON object. This is the JSON object I'm sending:
var user = {
Id: 1,
FirstName: 'Hello',
LastName: 'World',
CurrentAddress: {
Country: 'Israel',
City: 'Tel Aviv',
Street: 'Shalom',
Number: '5'
}
};
What I get in my Post method is a UserModel with the UserModel fields filled with the correct information, the CurrentAddrent address is initialized, but the values sent are not there. The values of the parent object (the UserModel object are ok).
What am I doing wrong here? how can you send a complex object to WebAPI Model?
to receive complex data objects in MVC web API actions you have to add [FromBody] attribute to your POST arguments.
The [FromBody] tells the Web API to search for the parameter’s value in the body of a POST request.
[HttpPost]
public void Post([FromBody] UserModel userModel)
{
}
I've made a local test and I obtained the values.
I hope it helps!

Categories

Resources