3

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?

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

Comments

-1

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/

3 Comments

$.post is the case of $.ajax. And this code doesn't work for me.
This code is not meant to replace yours. It's just an example of how I tend to do my ajax requests. Can you please paste your form HTML?
Also, what version of jQuery are you using?
-1

Try

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

.....

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.