Post array of strings to web API method

前端 未结 7 1311
伪装坚强ぢ
伪装坚强ぢ 2021-02-14 14:42

this is my client side ajax call:

    var list = [\"a\", \"b\", \"c\", \"d\"];

    var jsonText = { data: list };

    $.ajax({
        type: \         


        
7条回答
  •  臣服心动
    2021-02-14 15:08

    Setting the dataType won't help you.

    This is how I do it :

    var SizeSequence = {};
    SizeSequence.Id = parseInt(document.querySelector("dd#Sequence_Id").textContent);
    SizeSequence.IncludedSizes = [];
    var sizes = document.querySelectorAll("table#IncludedElements td#Size_Name");
    // skipping the first row (template)
    for (var i = 1, l = sizes.length ; i != sizes.length ; SizeSequence.IncludedSizes.push(sizes[i++].textContent));
    
    $.ajax("/api/SizeSequence/" + SizeSequence.Id, { 
         method: "POST",
         contentType: "application/json; charset=UTF-8",
         data: JSON.stringify(SizeSequence.IncludedSizes), 
    ...
    

    The Server Part

    // /api/SizeSequence/5
    public async Task PostSaveSizeSequence(int? Id, List IncludedSizes)
        {
            if (Id == null || IncludedSizes == null || IncludedSizes.Exists( s => String.IsNullOrWhiteSpace(s)))
                return BadRequest();
            try
            {
    
                await this.Repo.SaveSizeSequenceAsync(Id.Value, IncludedSizes );
                return Ok();
            }
            catch ( Exception exc)
            {
                return Conflict();
            }
        }
    

    References

    jQuery.ajax()

提交回复
热议问题