将javascript代码中的字符串发布到服务器上的ApiController

时间:2013-04-11 20:19:11

标签: javascript c# asp.net-mvc post

我开始使用ASP.NET Web API。当我在下一个Controler中获取我的实体时,我想知道序列化功能:

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);
    }
}

并在JavaScript方面:

// create new entity.
$.post("api/entities", $(formElement).serialize(), "json")
    .done(function (newEntity) { self.contacts.push(newEntity); });

但我不需要实体。我想收到字符串。所以我以下一种方式改变了控制器:

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);
    }
}

我为post function尝试了不同的dataType"json""text""html")。不同的data代表$(formElement).serialize()"simple Text"jsonObjectJSON.stringify(jsonObject)。但我始终在null操作中将entity作为Post参数在服务器端获得。

我做错了什么?

3 个答案:

答案 0 :(得分:4)

如果您想将表单数据发布为字符串,则需要执行以下两项操作:

默认情况下,Web API会尝试从请求URI中获取intstring等简单类型。您需要使用FromBody属性告诉Web API从请求正文中读取值:

public HttpResponseMessage Post([FromBody]string entity)
{
   //...
}

您需要使用空键发布您的值:

$.post("api/entities", { "": $(formElement).serialize() }, "json")
    .done(function (newEntity) { self.contacts.push(newEntity); });

您可以阅读有关此Web.API教程文章的更多信息:Sending HTML Form Data

答案 1 :(得分:-1)

您是否可以发布用于序列化的表单的HTML?我猜你错过了你选择的特定元素的name属性。

至于AJAX请求,我倾向于使用Kyle Schaeffer的“完美的ajax请求”模板;它更具可读性,并允许更好的结果处理恕我直言,至少在旧版本的jQuery中。

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

请参阅:http://kyleschaeffer.com/development/the-perfect-jquery-ajax-request/

答案 2 :(得分:-1)

尝试

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

.....