RredCat
RredCat

Reputation: 5421

Post string from javascript code to ApiController on server

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?

Upvotes: 3

Views: 2966

Answers (3)

Imp0ssible
Imp0ssible

Reputation: 49

Try

$.ajax({
  type: 'POST',
  url: 'api/entities',
   traditional: true,

.....

Upvotes: -1

nemesv
nemesv

Reputation: 139768

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

Upvotes: 4

RHarrington
RHarrington

Reputation: 1049

Could you post the HTML for the form that you're using with serialize? I'm guessing you're missing the name attribute from the particular element you are selecting.

As for the AJAX request, I tend to use the "perfect ajax request" template by Kyle Schaeffer; It's more readable and allows for better result handling IMHO, at least in older versions of jQuery.

$.ajax({
  type: 'POST',
  url: 'api/entities',
  data: { postVar1: 'theValue1', postVar2: 'theValue2' },
  beforeSend:function(){
  },
  success:function(data){
  },
  error:function(){
  }
});

Refer to: http://kyleschaeffer.com/development/the-perfect-jquery-ajax-request/

Upvotes: -1

Related Questions