L Me L Me - 6 days ago 6
Javascript Question

Pass Javascript array to the back end with post

I am trying to pass a java script array to the back end. But apparently I am not expecting the right type in the back end. What type i should expect. I added the delete method as well. Do I need to iterate in this array to be able to delete records?

[{"questionId":135,"answer":"A6.1"},{"questionId":135,"answer":"A6.2"}]


function deleteAnswers(arrayToDelete) {

$http.post(baseUrl + "Admin/deleteAnswers", {data: arrayToDelete})
.success(function (data, status, headers, config) {})
}


[HttpPost]
public ActionResult deleteAnswers(string data)
{
Console.Write(data);
Response.StatusCode = 200;
return Content("Sucess");
}


public void deleteAnswers(dynamic answersToDelete)
{
try
{
using (TestEntities testEntity = new TestEntities())
{
foreach (var item in answersToDelete)
{
Console.Write(item.);
//remove from
}

testEntity.SaveChanges();
}
}
catch (Exception ex)
{
Console.Write(ex);
}
}

Answer

You are sending an object with a property data with an array value, so your signature should look something like this:

[HttpPost]
public ActionResult deleteAnswers(MyObject data)
{
    Console.Write(data);
    Response.StatusCode = 200;
    return Content("Sucess");
}

public class MyObject {
    public List<Answer> Data { get; set; }
}

public class Answer {
    public int QuestionId { get; set; }
    public string Answer { get; set; }
}