I have my api which has a post method that looks like this:

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

and I call it by doing this:

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

When I do this, I get a 400 Bad Request response. If I put a breakpoint in my api method I find that Name is null. Here is my collection model:

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

Now, I have looked at this article:

Using jquery to post frombody parameters to web api

and it tells me that I need to send my parameters with an empty key, but I can't really do that with my Collection.

Does anyone know how to get around this? Or perhaps a better approach?

Any help would be greatly appreciated.

/r3plica

有帮助吗?

解决方案

Try using jQuery.ajax() method like this, This should work :-

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

             $.ajax({
                    type: "POST",
                    dataType: "json",
                    url: url,
                    data: myData,
                    success: function (data) {
                        alert(data);
                    }
                });
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top