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...
Related
I'm trying to pass a object which has multiple objects inside it as below
[Object, Object, Object, Object]
0
:
Object
ProductID
:
"50"
__proto__
:
Object
1
:
Object
BrandID
:
24
__proto__
:
Object
2
:
Object
BrandID
:
26
__proto__
:
Object
3
:
Object
BrandID
:
20
__proto__
:
Object
One of these objects has different key value pair than the others. How can I get capture this data from a Web Api controller. How should I modify my Model in the Web Api project.
It seems to me that the array you are trying to send to Web API contains different objects with different schemas. This approach is certainly error prone, and will not allow you to use ModelBinding properly.
Why don't you change the format of your object to something like this?
$scope.myObject = {
ProductID: 50,
BrandIDs: [24, 26, 20]
};
Using this kind of object you will be able to bind it to a strongly typed model in Web API.
public class MyModel {
public int ProductID { get; set; }
public List<int> BrandIDs { get; set; }
}
public IHttpActionResult Post(MyModel model) {
var productId = model.ProductID;
foreach(var brandId in model.BrandIDs) {
DoSomething(brandId);
}
return Ok();
}
You just need to create a class model that corresponds to you JSON and Web Api will automatically bind it. It seems that what you are passing is an array, so you can do something like that:
public void Execute(Model[] input)
{
}
....
public class Model
{
public int? ProductId {get;set;}
public int? BrandId {get;set;}
}
Or if you want one object with an array inside you can pass a class like that
public class ProductsContainer
{
public Product[] Products {get;set;}
}
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);
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.
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!
I need to pass a complex object representing a data filter to an action using GET which returns a filtered data set in a csv file.
The filter object is something like this on the client (much more complex in actuality, simplified for brevity):
var filter = {
Folders = [
{ Positive: true, Reference: { Id: 19, Name: "Container" } },
{ Positive: true, Reference: { Id: 37, Name: "Bullseye" } },
]
}
The corresponding server side classes look something like this:
public class MyFilter
{
public List<MyComparison> Folders { get; set; }
}
public class MyComparison
{
public bool Positive { get; set; }
public MyReference Reference { get; set; }
}
public class MyReference
{
public int Id { get; set; }
public string Name {get; set; }
}
My action looks like this:
[HttpGet]
public FileContentResult Export(MyFilter filter, string sort, bool sortAscending)
{
string data = GetCsvData(filter, sort, sortAscending);
return this.File(StrToByteArray(data), "text/csv", "Data.csv");
}
I have tried calling this action from javascript like this:
function exportFilter(aFilter) {
var params = { filter: aFilter, sort: "Name", sortAscending: true };
var destination = "MyController/Export?" + decodeURIComponent($.param(params));
document.location = destination;
}
Within the action, both the sort and sortAscending parameters are properly populated. The filter is an object of type MyFilter, but its Folders property is null.
Is ASP.NET MVC incapable of properly deserializing complex parameters in this way (ie in the context of a GET)? What is the correct way to address this problem?
The databinding algorithm in Asp.net MVC is not very good in deserializing complex inputs in .NET types. In the best scenario, you would get some strange results and/or slow performance compared to other dedicated solutions. In this case, Json.NET provides much better results at deserializing json data in .NET types, and its very fast too.
You should pass these filters like an ordinary string parameter and, inside the action, deserialize it using Json.NET. Something like this:
using Newtonsoft.Json;
public ActionResult MyAction(string myFilters)
{
var deserializedObject = JsonConvert.DeserializeObject(myFilters);
}
It can bind complex objects/parameters, the problem is the way the params are being sent. For example, you're sending:
http://localhost/Home/Export?filter[Folders][0][Positive]=true&filter[Folders][0][Reference][Id]=19&filter[Folders][0][Reference][Name]=Container&filter[Folders][1][Positive]=true&filter[Folders][1][Reference][Id]=37&filter[Folders][1][Reference][Name]=Bullseye&sort=Name&sortAscending=true
But the MVC model binder expects this format:
http://localhost/Home/Export?filter.Folders[0].Positive=true&filter.Folders[0].Reference.Id=19&filter.Folders[0].Reference.Name=Container&filter.Folders[1].Positive=true&filter.Folders[1].Reference.Id=37&filter.Folders[1].Reference.Name=Bullseye&sort=Name&sortAscending=true
I'm not sure of the easiest way to build a string matching that pattern from a javascript object though.