Reputation:
Working on some little task I have some troubles with the Web API controller.
There are 2 methods in my API:
[HttpGet]
public IHttpActionResult FetchAll()
[HttpPost]
public IHttpActionResult CreateNew(int? taskType, string taskName = null)
Which, I'm using for managing tasks in db. The 1st one (FetchAll) works fine as from special utilities like Postman and bringing some results to the browser console.
But! If to use the 2nd one (CreateNew) there are some problems.
As I have tested in Postman, it works fine:
But if to use my frontend part of application (JS):
var App = function () {
this.init();
};
App.prototype.init = function () {
var self = this;
$.post(
'/api/task/createNew',
{ taskName: "smth new", taskType: 0 }
);
$.get(
'/api/task/fetchAll',
function ( sender ) {
console.log(sender);
}
);
};
window.onload = function () {
var app = new App();
};
There is a problem with the POST method. Firstly I think I'm using jQuery not correctly, but reading the following links I understand that all is correct with jQuery use:
Also I've checked in browser the failed request details:
As you're able to see, the POST data have been transferred correctly with my jQuery use,
but I have also admit one detail: it's form data
.
So... Form data is a type of data, which is send with application/x-www-form-urlencoded
and isn't presented as URL part.
If to use in JS-part the next code:
$.post( '/api/task/createNew?taskName=smth new&taskType=0' );
All begins to work.
And Web API seems to be not supporting operations with the Forms
data and that's why the Postman test works well (if to look again at old screenshot), because it uses URL parameters, nor forms one.
But I think to send POST data with using URL parameters is rather ugly as for REST architecture and as for using it in JavaScript code (you will generate a string and not normally using Object
representation for data, which can be reviews as bad OO-structure).
I have read about forms handling in WebAPI here: Is there a way to handle form post data in a Web Api controller?
So do exist some ways to solve my problem with more pretty code-style etc (it's meant not to generate URL strings and etc)?
PS
Projects files which were described here are available:
Upvotes: 0
Views: 171
Reputation: 35793
As explained in the question you linked to your web api post action should take a object containing the fields you want:
public IHttpActionResult CreateNew(NewTask task)
{
// do something with task.TaskType and task.TaskName here
}
public class NewTask
{
public int? TaskType { get;set; }
public string TaskName { get; set; }
}
Upvotes: 1