【问题标题】:Post string from javascript code to ApiController on server将字符串从 javascript 代码发布到服务器上的 ApiController
【发布时间】:2013-04-11 20:19:10
【问题描述】:

我开始使用 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 function 尝试了不同的dataType"json""text""html")。和不同的data 表示$(formElement).serialize()"simple Text"jsonObjectJSON.stringify(jsonObject)。但我总是在服务器端获得null 作为Post 操作中的entity 参数。

我做错了什么?

【问题讨论】:

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


    【解决方案1】:

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

    默认情况下,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

    【讨论】:

    • 谢谢。你的文章很有用。
    【解决方案2】:

    您能否发布您在序列化中使用的表单的 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/

    【讨论】:

    • $.post 是 $.ajax 的情况。而且这段代码对我不起作用。
    • 此代码并非要替换您的代码。这只是我倾向于如何处理我的 ajax 请求的一个例子。你能粘贴你的表单 HTML 吗?
    • 另外,你用的是什么版本的jQuery?
    【解决方案3】:

    试试

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

    .....

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-03
      • 2015-10-20
      • 2014-11-23
      • 2018-01-06
      • 2018-12-18
      • 2023-03-30
      • 2017-08-03
      • 2019-10-07
      相关资源
      最近更新 更多