![](/img/trans.png)
[英]Post data from JavaScript to ApiController with POST method
[英]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"
, jsonObject
, JSON.stringify(jsonObject)
。 但我总是在服务器端获取null
作为Post
动作中的entity
参数。
我究竟做错了什么?
如果要将表单数据发布为字符串,则需要执行以下两项操作:
默认情况下,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表单数据
你可以发布你用于序列化的表单的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.