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

我尝试为post 功能dataType使用不同的( "json", "text", "html") 。和不同的表示, , , . 但我总是在服务器端作为操作中的参数。data$(formElement).serialize()"simple Text"jsonObjectJSON.stringify(jsonObject)nullentityPost

我究竟做错了什么?

4

3 回答 3

4

如果要将表单数据作为字符串发布,则需要做两件事:

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

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

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

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

您可以阅读有关此 Web.API 教程文章的更多信息:发送 HTML 表单数据

于 2013-04-11T20:52:17.050 回答
-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/

于 2013-04-11T20:23:38.590 回答
-1

尝试

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

......

于 2013-04-11T20:53:17.707 回答