3

Am trying to post an object that contains an array of strings in javascript to an API c# asp.net but the API receives that array as a single string for some reason instead as an array of strings. Please note that the only part that the issue occurs is email property Javascript code:

  vm =
    {
        title: $("#formTitle").val(),
        email: function () {
            var arr = [];
            document.getElementById("issueUserList").childNodes.forEach(function(child) {
                arr.push(child.innerText);
            });
            return arr;
        },
        urgencyFlag: parseInt($("#formUrgencyFlag").val()),
        completionFlag: parseInt($("#formCompletionFlag").val()),
        category: {
            id: $("#category").val(),
            description: $("#category :selected").attr("name")
        },
        issueTagsId: $("#tags").val().map(Number),
        description: $("#formDescription").val(),
        solution: $("#formSolution").val(),
        note: $("#formNote").val()
    }
    $.ajax({
            url: "/api/issues",
            method: "POST",
            data: vm
        })
        .done(function() {
            clearIssueForm();
            toastr.success("Issue recorded successfully");
        })
        .fail(function(xhr) {
            if (xhr.status === 404) {
                toastr.error(xhr.responseText
                    .replace("message", "User")
                    .replace("{", "")
                    .replace("}", ""));
            } else {
                console.log(xhr.responseText);
                toastr.error("something unexpected has occured. Please try again");
            }
        });
    }
});

Now when i debug this one it correctly builds an array of strings.

Api that should receive this code c#

[HttpPost]
public IHttpActionResult CreateIssue(IssueDto dto)
{




    var users = _context.Persons.Where(p => dto.Email.Contains(p.Email)).ToList();
    var issueTags = _context.IssueTagses.Where(
        t => dto.IssueTagsId.Contains(t.Id)).ToList();
    var issue = new Issue
    {
        Title = dto.Title,
        Description = dto.Description,
        Solution = dto.Solution,
        Note = dto.Note,
        UrgencyFlag = dto.UrgencyFlag,
        CompletionFlag = dto.CompletionFlag,
        DateIssueRegistered = DateTime.Now,
        LastUpdate = null,
        CategorieId = dto.Category.Id,
        Persons = users,
        IssueTagses = issueTags
    };
    _context.Issues.Add(issue);
    _context.SaveChanges();

    dto.Id = issue.Id;

    return Created(new Uri(Request.RequestUri +"/" + dto.Id), dto );
}

Structure of IssueDto

 public class IssueDto
{
   public int Id { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public string Solution { get; set; }
    public string Note { get; set; }
    public List<string> Email { get; set; } //Extra 


    public UrgencyFlag UrgencyFlag { get; set; }
    public CompletionFlag CompletionFlag { get; set; }

    public DateTime DateIssueRegistered { get; set; }
    public DateTime? LastUpdate { get; set; }

    public IssueCategorieDto Category { get; set; }
    public List<PersonDto> PersonDtos { get; set; }
    public List<IssueTagsDto> IssueTags { get; set; }
    public List<int> IssueTagsId { get; set; } // Extra info
    public int CategorieId { get; set; }

Then when posted to the api using jquery $.ajax the api translates this array to a single string as an example "name1,name2" instead of [name1],[name2]therefor my _context.Persons.Where code fails to find anything that matches that in the database as the user does't exist. Any ideas why that might happen or any additional information you need to understand the issue?

12
  • The code you've shown is just a function that returns an array? Wheres the rest of the code? Commented Jan 10, 2017 at 14:13
  • Yes and is received by a View model object that is later passed to the backend via an Ajax call i will fix that to make it more understandable Commented Jan 10, 2017 at 14:14
  • Right wheres that code? Commented Jan 10, 2017 at 14:15
  • Assuming you are using web api... please post your apicontroller code Commented Jan 10, 2017 at 14:16
  • 2
    Please create a Minimal, Complete, and Verifiable example Commented Jan 10, 2017 at 14:18

1 Answer 1

3

you need to invoke the function:-

vm = {
  title: $("#formTitle").val(),
  email: function() {
    var arr = [];
    document.getElementById("issueUserList").childNodes.forEach(function(child) {
      arr.push(child.innerText);
    });
    return arr;
  }(), // <--- HERE
  urgencyFlag: parseInt($("#formUrgencyFlag").val()),
  completionFlag: parseInt($("#formCompletionFlag").val()),
  category: {
    id: $("#category").val(),
    description: $("#category :selected").attr("name")
  },
  issueTagsId: $("#tags").val().map(Number),
  description: $("#formDescription").val(),
  solution: $("#formSolution").val(),
  note: $("#formNote").val()
}

This will then call the function as soon as the object is created, setting the property to an array.

Sign up to request clarification or add additional context in comments.

1 Comment

Well that was easier than expected, thanks for the help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.