How to pass a list of selected objects from javasc

2019-06-14 04:00发布

问题:

I have a large data table that contains a checkbox for each row. I need to either pass all items that are selected as either a comma delimited list, or better yet a strongly typed IList to the controller. What is the best way to accomplish this? I know I can pass a string with no issue, but how do I get which checkboxes are selected?

Here's what the static code looks like:

@using (@Html.BeginForm("RemoveItems", "ResultList", new { IDList = "1,2,3,4" }, FormMethod.Post))
{
    <input type="submit" value="Remove Items" name="RemoveItems" />
}

回答1:

You can do it like this using jQuery.

    $.ajax({
        url: "/MyAction/Array",
        data: JSON.stringify({ model: input }),
        type: "POST",
        contentType: "application/json"
    });

Here "input" is your array, "model" - name of action parameter. Make sure you've specified contentType as application/json.



回答2:

I have had a site maybe similar to your.

I had a table with checkboxes at each row.

What i did was:

var firstPriorityArray = new Array();

        $("Input:checkbox[name=FirstPriority]:checked").each(function () {

            firstPriorityArray[firstPriorityArray.length] = $(this).val();
            console.log(fp.toString());
        });

The console.log is only to be able to see what happend and how it looks :)

Afterwards i used JSON.Stringify() and a object and sent it back to another ASPX site with AJAX like this:

var o = new Object();
    o.primary = firstPriorityArray;

var json = JSON.stringify(o);
        $.ajax({
            url: 'getMeAJAX.aspx',
            type: 'POST',
            data: "json=" + json,
            success: function (response) {
                //On success
            },
            error: function (xhr, ajaxoptions, thrownError) {
                alert(thrownError);
            }
        });

Maybe you can use this or be inspired. I cant say if this is the "perfect" and most "MVC" way to do it, but it works ;)

//Gerner