Firkamon
Firkamon

Reputation: 807

MVC Razor Ajax get from jQuery

Currently I have the following jQuery code. When someone clicks on #docs, I send .selected rows to controller and get a model object back. As you can see, I just print it out with .append(). There has to be a better way to do this.

The problem is that the rows being sent are a DataTables object; so I haven't found a way to send that to Razor code yet. Is it possible?

I can't find a way to make Razor handle the Ajax using the DataTables rows. I'd like to have the actual object rather than an unreliable and ill-maintainable print-out of the object.

Is there a better way to go about this entirely?

$('#docs').click(function () {
        $.ajax({
            type: "POST",
            url: "/docs/send",
            data: {
                rows: JSON.stringify($(table.rows('.selected').data().toArray())),
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.status);
                alert(thrownError);
            }
        })
        .success(function (data) {
            var result = $.parseJSON(data);
            $("#documents").html("");
            $.each(result, function (key, value) {

                $('#documents').append(key+" "+value+"<br>")
            });
        });
    });

//

Controller code. Send calls Count. Count returns number of Doc objects which have the exact IDs given.

        public List<Doc> Count(string[] GRE, UpFile.ApplicationDbContext db)
        {
            var list = new List<Doc>(); 
            var count = 0;
            if (GRE.Length > 0)
            {
                foreach (var item in db.Docs)
                {
                    count = 0;
                    foreach (var device in item.Devices)
                    {
                        for (var i = 0; i < GRE.Length; i++)
                        {
                            if (GRE[i]!=null && device.gre != null)
                            {
                                if (GRE[i].Contains(device.gre))
                                {
                                    count++;
                                }
                            }
                        }
                    }
                    if (count == GRE.Length)
                    {
                        list.Add(item);
                    }
                }
            }

            return list;
        }


        public JsonResult Send(string rows)
        {
            var greID = new string[0];
        if (rows != null)
        {
            var count = 0;
            greID = new string[rows.Split(new string[] { ":[" },StringSplitOptions.None).Length-1];
            foreach (var row in rows.Split(':'))
            {
                var rowSplit = row.Split(',');
                for (var i = 0; i < rowSplit.Length; i++)
                {
                    if (rowSplit[i].Contains("GRE-"))
                    {
                        greID[count] = rowSplit[i];
                        count++;
                    }
                }
            }
        }
        var serializer = new JavaScriptSerializer();
        var serializedResult = serializer.Serialize(Count(greID,db).ToArray());
        return Json(serializedResult);

Upvotes: 0

Views: 484

Answers (2)

Casey
Casey

Reputation: 805

You're not going to be able to make the Razor code handle the Ajax. Razor code is server side so once that view is rendered in the browser there is no razor code on that page any longer. Only client side code such as the Ajax function.

My suggestion is to either build an API that returns the data row as JSON and have the Ajax handle or create a partial view that Ajax reloads.

Upvotes: 1

jgasiorowski
jgasiorowski

Reputation: 1033

I don't really know the case where that code works etc. But If you have table and user selects some rows - then request goes to server and server sends back detailed data about selected rows I would do this differently.

I usually extract from the row some unique value for particular element (like ID) and send only that value with AJAX. If you have multiple elements selected you can still format an array of IDs. Then on the server side you can use that ID to do the rest.

Upvotes: 0

Related Questions