使用Web Api和FromBody

时间:2014-02-18 11:34:27

标签: jquery asp.net-web-api frombodyattribute

我的api有一个post方法,如下所示:

// POST api/collections
public HttpResponseMessage Post([FromBody]Collection model)
{
    if (!ModelState.IsValid)
        return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);

    using (var uow = new UnitOfWork<SkipstoneContext>())
    {
        var service = new CollectionService(uow, User.Identity.GetUserId());

        service.Save(model);
        uow.SaveChanges();

        return Request.CreateResponse(HttpStatusCode.OK, model);
    }
}

我这样称呼它:

var data = '{ "Id": ' + id + ', "Name": "' + $('#Name').val() + '", "Description": "' + $('#Description').val() + '" }';
$.post(form.attr("action"), data);

当我这样做时,我收到 400 Bad Request 响应。如果我在api方法中放置断点,我发现名称为空。 这是我的收藏模型:

public partial class Collection
{
    public int Id { get; set; }
    public string CreatedById { get; set; }
    [Required] public string Name { get; set; }
    public string Description { get; set; }
    public System.DateTime DateCreated { get; set; }
    public string ModifiedById { get; set; }
    public Nullable<System.DateTime> DateModified { get; set; }

    public User CreatedBy { get; set; }
    public User ModifiedBy { get; set; }
    public ICollection<Asset> Assets { get; set; }
}

现在,我看过这篇文章:

Using jquery to post frombody parameters to web api

它告诉我,我需要用空键发送我的参数,但我不能用我的集合来实现这一点。

有谁知道怎么解决这个问题?或者更好的方法?

非常感谢任何帮助。

/ r3plica

1 个答案:

答案 0 :(得分:1)

尝试使用jQuery.ajax()这样的方法,这应该有效: -

            var myData = { 
                 'Id':  id, 
                 'Name':  $('#Name').val(), 
                 'Description': $('#Description').val() 
                };

             $.ajax({
                    type: "POST",
                    dataType: "json",
                    url: url,
                    data: myData,
                    success: function (data) {
                        alert(data);
                    }
                });