Post string from javascript code to ApiController on server
asp.net-mvc, c#, javascript, post
Solution
If you want to post your form data as a string you need to do two things:
By default, Web API tries to get simple types like `int`, `string` etc. from the request URI. You need to use `FromBody` attribute tells Web API to read the value from the request body:
public HttpResponseMessage Post([FromBody]string entity)
{
//...
}
And you need to post your value with an empty key:
$.post("api/entities", { "": $(formElement).serialize() }, "json")
.done(function (newEntity) { self.contacts.push(newEntity); });
You can read more about this Web.API tutorial article: Sending HTML Form Data
Problem
I start to play with ASP.NET Web API. I am wondering with serialization feature when I get my entity in the Controler like next: ``` public class EntitiesController : ApiController { [Queryable] public IEnumerable<Entity> Get() { return m_repository.GetAll(); } public HttpResponseMessage Post(Entity entity) { if (ModelState.IsValid) { m_repository.Post(entity); var response = Request.CreateResponse<Entity>(HttpStatusCode.Created, entity); return response; } return Request.CreateResponse(HttpStatusCode.BadRequest); } } ``` and on the JavaScript side: ``` // create new entity. $.post("api/entities", $(formElement).serialize(), "json") .done(function (newEntity) { self.contacts.push(newEntity); }); ``` But I don't need entity. I want to receive string. So I've changed controller in the next manner: ``` public class EntitiesController : ApiController { [Queryable] public IEnumerable<string> Get() { return m_repository.GetAll(); } public HttpResponseMessage Post(string entity) { if (ModelState.IsValid) { m_repository.Post(entity); var response = Request.CreateResponse<Entity>(HttpStatusCode.Created, entity); return response; } return Request.CreateResponse(HttpStatusCode.BadRequest); } } ``` I tried to different `dataType` (`"json"`, `"text"`, `"html"`) for post function. and different `data` representation `$(formElement).serialize()`, `"simple Text"`, `jsonObject`, `JSON.stringify(jsonObject)`. But I always get `null` on server side as `entity` parameter in the `Post` action. What am I doing wrong?