簡體   English   中英

將javascript代碼中的字符串發布到服務器上的ApiController

[英]Post string from javascript code to ApiController on server

我開始使用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函數 和不同的data表示$(formElement).serialize()"simple Text"jsonObjectJSON.stringify(jsonObject) 但我總是在服務器端獲取null作為Post動作中的entity參數。

我究竟做錯了什么?

如果要將表單數據發布為字符串,則需要執行以下兩項操作:

默認情況下,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教程文章的更多信息: 發送HTML表單數據

你可以發布你用於序列化的表單的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/

嘗試

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

.....

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM