0

I've been trying to find an answer on google without any result. My question is how can I manipulate my Json data (List<string>) in my view? I'd like to show all the string returned in a div for example.

Here's where I'm currently stuck at:

CONTROLLER

    [HttpPost]
    public async Task<ActionResult> RetournerOP(int OF)
    {
        List<string> ops = new List<string>();
        Task verif = Task.Run(() =>
        {
            try
            {
                connection.Open();
                string sqlQuery = "SELECT Operation from ZZ where ordre = " + OF;
                SqlCommand command = new SqlCommand(sqlQuery, connection);
                using (SqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        ops.Add(Convert.ToString(reader["Operation"]));
                    }
                }
            }
            catch (Exception) { }
            finally { connection.Close(); }
        });
        await verif;
        return Json(ops);
    }

VIEW

function retournerOp() {
    $.ajax({
        url: '@Url.Action("RetournerOp", "Home", new { area = "Ajout" })',
        data: {OF: document.getElementById("NumOf").value},
        type: 'POST',
        dataType: 'JSON',
        cache: false,
        success: function (data) {
            //How can I manipulate my data returned?
        }
    });
}
5
  • 2
    Did you try looping through data and use it ? $.each(data,function(a,b){ //do something }); Commented Jul 11, 2017 at 14:45
  • 1
    you have two options - either return a pre-populated view to your ajax response and inject it in your HTML OR use some kind of data binding library to patch your JSON collection with a html template at client-side. Commented Jul 11, 2017 at 14:45
  • Can you show your html template? Commented Jul 11, 2017 at 14:51
  • 1
    And please use parameterized queries, instead of concatenated strings. Commented Jul 11, 2017 at 14:55
  • @Stephen I'll go read on that! Commented Jul 11, 2017 at 15:01

1 Answer 1

1

Your server action method is currently returning an array of strings. So in your ajax call's success callback, you may loop through them and use each item as needed ( like adding to your DOM). $.each method will be handy to loop.

For example, the below code loops through the array and wrap each item in a p tag and append the list of p tags to a div with id myDivId

success: function (data) {
    var t = "<div>";
    $.each(data,function(a, b) {
                t += '<p>'+b+'</p>';
        });
    $("#myDivId").html(t);
}

If you want to render a more complex html markup, i would strongly advise creating an action method (if you cannot update the existing one because other code is already using it) which returns a partial view result instead of the json. So you will pass the list of strings to the partia view and the partial view will have the code to render the sophisticated markup you want to return.

return PartialView(ops);

and in the partial view,

@model List<string>
@foreach (var item in Model)
{
    <p>@item</p>
}

Now since the response coming from the server call is the HTML markup you want, simply update the DOM with that as needed.

$.ajax({
     url: '@Url.Action("RetournerOp", "Home", new { area = "Ajout" })',
    data: {OF:6},
    type: 'POST',
    success: function (data) {
        $("#myDivId").html(data);
    }
});

Also as others mentioned in the comments, your server code is prone to SQL injection. You should never concatenate the user input directly to a SQL statement like that. Consider using Parameterized queries.

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

2 Comments

Might be worth editing your answer to include a correction to the OP's glaring SQL injection vulnerability.
Thanks for the detailed answer, really helped me out! I'll go read on parameterized queries as well.

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.