October 2018 - Digital Tool Factory blog October 2018 - Digital Tool Factory blog

The Digital Tool Factory Blog

How to post objects directly to web api from C#

As I’ve looked this up three times now I should put the code directly on the blog. Happily Microsoft has done a lot of the plumbing work for you.

You have a Web API controller with an action that looks like this
[System.Web.Http.Route("Ajax/v1.1/PostItemBatch")]
[OutputCache(NoStore = true, Duration = 0)]
[System.Web.Http.HttpPostAttribute]
public bool PostItemBatch(List postItems)
{
using (ApplicationDbContext db = new ApplicationDbContext())
{
foreach (PostItem postItem in postItems)
{
db.PostItems.Add(postItem);
}
db.SaveChanges();
return true;
}
}

Then you can post data to it by the following

List PostItems = new List();
for (int i = 0; i < 11; i++)
{
PostItems.Add(new PostItem(true));
}

HttpClient client = new HttpClient();
HttpResponseMessage response = client.PostAsJsonAsync("http://localhost:56168/Ajax/v1.1/PostPostItemBatch", PostItems).Result;
var test = response.IsSuccessStatusCode;

And there you go!


15
Oct 18


Written By Steve French

 

How to fix problems with jquery data tables and a list of objects from ASP.net Web API

The main problem is that data tables does not expect a list of objects, instead it wants a differently formatted json object, something like

data: {“Property”: Value}

etc
Instead it’s getting a pure list, like this

[
{“Name”:”Value},
{“Name”:”Value},
{“Name”:”Value},
{“Name”:”Value},
{“Name”:”Value},
]

Solution – list out the values in the columns property of the data table, like this

$(document).ready(function () {
$(‘#example’).dataTable({
“deferRender”: true,
“processing”: true,
“iDisplayLength”: 25,
“ajax”: {
“url”: “https://domain.com/Ajax/v1.1/ListTypes”,
“dataSrc”: “”
},
“columns”: [
{ “data”: “Name” },
{ “data”: “OtherColumn” }
]
});
});

And you’re done!


10
Oct 18


Written By Steve French

 




Copyright 2011 Digital Tool Factory. All Rights Reserved. Powered by raw technical talent. And in this case, WordPress.