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

问题描述 投票:3回答:3

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

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

我尝试将dataType"json""text""html")用于post function。和不同的data表示$(formElement).serialize()"simple Text"jsonObjectJSON.stringify(jsonObject)。但我总是在服务器端获得null作为entity行动中的Post参数。

我究竟做错了什么?

javascript c# asp.net-mvc post
3个回答
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
投票

你可以发布你用于序列化的表单的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/


-1
投票

尝试

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

.....

© www.soinside.com 2019 - 2024. All rights reserved.