简体   繁体   English

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

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

I start to play with ASP.NET Web API. 我开始使用ASP.NET Web API。 I am wondering with serialization feature when I get my entity in the Controler like next: 当我在下一个控制器中获取我的实体时,我想知道序列化功能:

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

and on the JavaScript side: 在JavaScript方面:

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

But I don't need entity. 但我不需要实体。 I want to receive string. 我想收到字符串。 So I've changed controller in the next manner: 所以我以下一种方式改变了控制器:

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

I tried to different dataType ( "json" , "text" , "html" ) for post function . 我尝试使用不同的dataType"json""text""html" )作为post函数 and different data representation $(formElement).serialize() , "simple Text" , jsonObject , JSON.stringify(jsonObject) . 和不同的data表示$(formElement).serialize()"simple Text"jsonObjectJSON.stringify(jsonObject) But I always get null on server side as entity parameter in the Post action. 但我总是在服务器端获取null作为Post动作中的entity参数。

What am I doing wrong? 我究竟做错了什么?

If you want to post your form data as a string you need to do two things: 如果要将表单数据发布为字符串,则需要执行以下两项操作:

By default, Web API tries to get simple types like int , string etc. from the request URI. 默认情况下,Web API尝试从请求URI中获取intstring等简单类型。 You need to use FromBody attribute tells Web API to read the value from the request body: 您需要使用FromBody属性告诉Web API从请求正文中读取值:

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

And you need to post your value with an empty key: 您需要使用空键发布您的值:

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

You can read more about this Web.API tutorial article: Sending HTML Form Data 您可以阅读有关此Web.API教程文章的更多信息: 发送HTML表单数据

Could you post the HTML for the form that you're using with serialize? 你可以发布你用于序列化的表单的HTML吗? I'm guessing you're missing the name attribute from the particular element you are selecting. 我猜你错过了你选择的特定元素的name属性。

As for the AJAX request, I tend to use the "perfect ajax request" template by Kyle Schaeffer; 至于AJAX请求,我倾向于使用Kyle Schaeffer的“完美的ajax请求”模板; It's more readable and allows for better result handling IMHO, at least in older versions of jQuery. 它更具可读性,并允许更好的结果处理恕我直言,至少在旧版本的jQuery中。

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

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

Try 尝试

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

..... .....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM