使用jquery ajax将复杂的DTO发送到web api

时间:2014-09-04 13:22:07

标签: c# jquery ajax asp.net-web-api

我有这样的DTO对象:

public class ImageDto : EntityDTO
{
    public ImageDto()
    {
        Position = new PositionDTO();
        Rotation = new RotationDTO();
        Size = new SizeDTO();
    }

    public string Name { get; set; }
    public string Source { get; set; }
    public string Description { get; set; }
    public string Style { get; set; }
    public string Link { get; set; }
    public int ZIndex { get; set; }
    public string Effect { get; set; }
    public PositionDTO Position { get; set; }
    public RotationDTO Rotation { get; set; }
    public SizeDTO Size { get; set; }

}

我有一个像这样的方法的Web Api:

    // POST api/Image/CreateImage
    [HttpPost]
    [Route("CreateImage")]
    public IHttpActionResult CreateImage([FromBody]ImageDto imageDto)
    {
        if (imageDto == null)
            return BadRequest();

        return Ok();

    }

当我尝试从Jquery Ajax发送DTO时,复杂类型的值(PositionDTO,RotationDTO和SizeDTO始终为0.0)

这是我使用jQuery AJAX的代码:

var urlApi = '/api/Image/CreateImage';

    var imageDTO =
    {
        Name: "",
        Source: "",
        Description: "",
        IdSlide: "9aa2d084-dd82-457b-a80d-9af8375c59ff",
        Style: "",
        Link: "",
        ZIndex: "",
        Effect: "",
        SizeDTO: {
            Width: 200,
            Height: 200,
        },
        PositionDTO: {
            PositionLeft: 200,
            PositionTop: 200,
        },

        RotationDTO: { Rotation: 180 },

        IdGenially: "54006b50b59f86143834c187"

    };

    function getData() {
        return $.ajax({
            url: urlApi,
            type: 'POST',
            data: JSON.stringify(imageDTO),
            contentType: "application/json; charset=utf-8"
        });
    }

如何在JavaScript中获取DTO对象的值而不是所有复杂值的0.0?其他值也很好。

此致!!

1 个答案:

答案 0 :(得分:2)

您的课程没有 * DTO 属性,您的属性为:PositionRotationSize

public PositionDTO Position { get; set; }
public RotationDTO Rotation { get; set; }
public SizeDTO Size { get; set; }

尝试从您的名字中删除DTO:

    Size: {
        Width: 200,
        Height: 200,
    },
    Position: {
        PositionLeft: 200,
        PositionTop: 200,
    },

    Rotation: { Rotation: 180 },