how to post objects from angular to a webapi controller - javascript

I am creating a pdf using pdfsharp. I need to pass the chart legend data(name,color) to the pdfsharp controller. I am using a angular $http post, a ajax post would be fine as well. the error I am getting is
Request URL:http://localhost:46691/api/exportChartPdf/[object%20Object],[object%20Object],[object%20Object],[object%20Object],[object%20Object],[object%20Object],[object%20Object],[object%20Object],[object%20Object],[object%20Object],[object%20Object],[object%20Object],[object%20Object],[object%20Object],[object%20Object],[object%20Object]
do i need to some how pass it as a string? if so how would I parse it in the api controller back to the way I need it?
the objects i am trying to pass back
0: Object
color: "rgb(67,134,215)"
name: "Fleming Place - Miscellaneous Spec Builders"
__proto__: Object
1: Object
2: Object
3: Object
4: Object
javascript
var legendModel = $scope.seriesData.map(function (a) {
return {
color: a.color,
name: a.name
};
});
$http.post('/api/exportChartPdf/' + legendModel);
api controller
[HttpPost]
public PDF Post() // allow nullable parameter
{
try
{

You should be posting the object on the form body, not on the querystring. In addition, your Web API controller should receive a strongly typed object that mirrors the data that you're passing.
public class Data
{
public string Color { get; set; }
public string Name { get; set; }
}
[HttpPost]
public PDF Post([FromBody]List<Data> data)
{
...
}
And then simply post the object.
var legendModel = $scope.seriesData.map(function (a) {
return {
color: a.color,
name: a.name
};
});
$http.post('/api/exportChartPdf/', legendModel);

Looks like your controller action is missing parameter on it,
[HttpPost]
public PDF Post(SomeClass legendModel) // allow nullable parameter
{
try
{
SomeClass would contain color & name properties.
Then you should correct your $http.post call, pass 2nd param as data in JSON format.
$http.post('/api/exportChartPdf', { legendModel: legendModel);

Related

How to capture a $scope object with multiple objects from web api

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

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

How to post an object to WebAPI

I'm trying to figure out how to post an object from my form to a web api service. Within my controller I defined a model that I wanted to add input values to.
$scope.Label;
within my input fields I have them bound using ng-model such as:
<input type="checkbox" ng-model="label.isPublic" />
<input type="text" ng-model="label.labelName" required focus-me />
On the submission of the form these two fields a passed to my service and submitted to my WebApi
I have tried this submission in two ways:
function addLabel(label) {
var mylabel = encodeURIComponent(angular.toJson(label));
return $http.post('reportLibrary/createlabel/', { params: label }, {
}).then(function (response) {
return response.data;
});
};
and also as the following without declaring parameters
function addLabel(label) {
var mylabel = encodeURIComponent(angular.toJson(label));
return $http.post('reportLibrary/createlabel/', label , {
}).then(function (response) {
return response.data;
});
};
In the webAPI I have a method setup for the post
[Route ("reportLibrary/createlabel/")]
[HttpPost]
public DTOs.ReportLabel CreateLabel(DTOs.ReportLabel json)
{
DTOs.ReportLabel result = new DTOs.ReportLabel();
//.... do stuff
return result;
}
The ReportLabel (dto) is defined as follows:
public class ReportLabel
{
public Int64 LabelId { get; set; }
public string LabelName { get; set; }
public bool IsPublic { get; set; }
public IEnumerable<Report> Reports { get; set; }//placeholder?
}
The issue I have is when I post an object from my angular service it shows up as null within the API. If I change the type in the method to something like a JToken or JObject the values appear.
Can anyone help me understand why when I define the type that it is not passed across from angular?
thanks
It seems like you may be doing an extra step. You don't need to encode in json then pass in in json
return $http.post('reportLibrary/createlabel/', { LabelId: 101, LabelName: 'myname' }, {
then
public DTOs.ReportLabel CreateLabel([FromBody]ReportLabel reportLabel)
Take a look at the network values going by and you should see in debug tools or fiddler the actual posted values (form values).

How to post DbGeography param to MVC?

I am trying to expose an API that will allow users to post polygons to persist on the server. I am using ASP.NET MVC 5. How do I format the AJAX parameters correctly to post the request for DbGeography? This is what I am trying:
$.ajax({
url: '/api/map',
type: 'POST',
data: {
Title: 'My Title',
MyGEOG: {
WellKnownText: 'POLYGON ((30 10, 10 20, 20 40, 40 40, 30 10))'
}
}
});
This is how my MVC action signature looks like:
[HttpPost]
[Route("map")]
public JsonResult Post(MyShape newShape) {...}
Also my MyShape class:
public class MapShape
{
public string Title { get; set; }
public System.Data.Entity.Spatial.DbGeography MyGEOG { get; set; }
}
When putting a breakpoint in the action, newShape.Title does show as My Title, but MyGEOG is null when the AJAX post happens. What is the correct format of the parameter to post correctly as a DbGeography type?
The reason the DBGeography object is immutable, meaning that you can't write to it once it has been created. When you instantiate your MapShape class in the model binder, the MyGEO property is null. In other words, you are trying to set a property on a null object.
The only way to "create" a DBGeography object is using one of the factory methods like:
FromText - Creates a new DbGeometry value based on the specified well known text value.
http://msdn.microsoft.com/en-us/library/hh673669(v=vs.110).aspx
So, to pass in the Title and WellKnownText values to you controller, I suggest creating a Data Transfer Object (DTO) to act as proxy for the information.
public class MapShapeDTO
{
public string Title { get; set; }
public string WellKnownText { get; set; }
}
Your Ajax gets simplified like this
$.ajax({
url: '/api/map',
type: 'POST',
data: {
Title: 'My Title',
WellKnownText: 'POLYGON ((30 10, 10 20, 20 40, 40 40, 30 10))'
}
});
And your controller, you can use the DTO to create the MapShape object.
[HttpPost]
[Route("map")]
public JsonResult Post(MapShapeDTO dto)
{
MapShape m = new MapShape()
{
Title = dto.Title,
MyGEOG = System.Data.Entity.Spatial.DbGeography.FromText(dto.WellKnownText)
};
...
}

ASP.NET MVC: GET params not properly deserialized

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.

Categories

Resources