简体   繁体   中英

WebApi Parameter is not null but has empty values

This is the default webapi method with [FromBody] attribute added:

// PUT api/Pedidos/5
    public async Task<IHttpActionResult> PutPedido(Guid id,[FromBody]Job pedido)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        if (id != pedido.Id)
        {
            return BadRequest();
        }

        db.Entry(pedido).State = EntityState.Modified;

        try
        {
            await db.SaveChangesAsync();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!PedidoExists(id))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }

        return StatusCode(HttpStatusCode.NoContent);
    }

this is the jquery request:

self.update = function () {                
            $.ajax({
                type: "PUT",
                url: baseUri + '@Model.Id',
                data: ko.toJSON(updatableData),                    
                dataType: "json",
                contentType: "application/json"
            })
                .done(function (data) {

                    alert('Magic');
                })
                .error(function (jqXHR, textStatus, errorThrown) {
                    alert(errorThrown);
                    alert("fail");
                });
        }

This is the data:

var updatableData = {
            Id : '@Model.Id',
            Name : '@Model.Name',
            AbreviaNome: self.AbreviaNome(),
            AbreviaFantasia: self.AbreviaFantasia,
            AbreviaLogradouro: self.AbreviaLogradouro,
            AbreviaComplemento: self.AbreviaComplemento,
            AbreviaBairro: self.AbreviaBairro,
            AbreviaCidade: self.AbreviaCidade,
            AbreviaExtra: self.AbreviaExtra,
        };

this is partial c# model, I have removed about 7 fields where 2 are dates and the rest are strings:

public class Job
{       
    public Guid Id { get; set; } 
    [Required]   
    public string Name {get;set;}    
    public int TotalItems { get; set; }        
    public bool AbreviaNome { get; set; }
    public bool AbreviaFantasia { get; set; }
    public bool AbreviaLogradouro { get; set; }
    public bool AbreviaComplemento { get; set; }
    public bool AbreviaBairro { get; set; }
    public bool AbreviaCidade { get; set; }
    public bool AbreviaExtra { get; set; }
    public virtual ICollection<Item> Items { get; set; }        
}

I using ASP.NET with knockout.js thats why you see 'self' on the data. the request comes through, and I get to the PUT method just fine. But pedido instance has all false values and no Id at all (only on the first parameter), and all values were supposed to come as true, with the exception of the last one, on the attempt I had, see the Request Body content:

{"Id":"c47f0ad2-0783-e311-8289-88532ee08d00", "Name":"Test 1","AbreviaNome":true,"AbreviaFantasia":true,"AbreviaLogradouro":true,"AbreviaComplemento":true,"AbreviaBairro":true,"AbreviaCidade":true,"AbreviaExtra":false}

What might be happening here? Do I have to have all fields on the "updatableData" object? Is there another way of achieving what I need?

EDIT: I have added a field to model that was missing but its important "Name" is a required field and there is an error somewhere that it thinks that the Name value is not on the request, when it actually is, after the correction.

EDIT: Found an error in the ModelBinding, related to the Required Name:

{"$id":"1","Message":"The request is invalid.","ModelState":{"$id":"2","pedido.Name":["The Name field is required."]}}

I have removed the [Required] attribute from the Name property, then it stopped working worse, in the ModelBinding I was getting only one parameter, which was the Id. When I put required back it goes back to working but with the above error.

Try to use JSON.stringify instead of ko.ToJSON :

self.update = function () {                
            $.ajax({
                type: "PUT",
                url: baseUri + '@Model.Id',
                data: JSON.stringify(updatableData),                    
                datatype: "json",
                contenttype: "application/json"
            })
                .done(function (data) {
                alert('Magic');
            })
            .error(function (jqXHR, textStatus, errorThrown) {
                alert(errorThrown);
                alert("fail");
            });
    }

Also, you appear to be passing one object over but expecting 2 parameters, so you shouldn't need the Guid id on the method signature as it's in the Job object already:

public async Task<IHttpActionResult> PutPedido([FromBody]Job pedido)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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