简体   繁体   中英

Return data using JavaScript from view to controller in MVC

I have WCF service that should be consumed by a MVC app. Now I want to delete items from a list using checkbox. When I receive data in my controller, the first WCF method that is called (findAccRoleMapp) should find all data in the table and then call another WCF method (removeAccForRole) to delete that data.

Here is my controller:

    [HttpGet]
    public ActionResult GetAccForRol(string id)
    {
        AccountManagementServiceClient amsc = new AccountManagementServiceClient();
        ViewBag.listAccForRol = amsc.findAllAccByRol(id);
        return View();

    }

    [HttpPost]
    public ActionResult GetAccForRol(FormCollection collection)
    { 
        AccountManagementServiceClient amsc = new AccountManagementServiceClient();
        AccountManagementViewModel amvm = new AccountManagementViewModel();

        foreach(var item in collection)
        {
            if(collection != null)
            {
            string object= item.ToString();
            var accounts = amsc.findAccRoleMapp(object);
            amsc.removeAccFromRole(accounts);
            }
        }
        return RedirectToAction("GetAccForRol");
    }

Here is the JS what i have in my view:

    <script type="text/javascript" src="@Url.Content("~/Scripts/")jquery-1.10.2.js"></script>

<script type="text/javascript">

    var container = []; 
    counter = 0;

$(document).ready(function () {

    $('#checkBoxAll').click(function () {
        if ($(this).is(":checked"))
            $('.chkCheckBoxId').prop('checked', true);
        else
            $('.chkCheckBoxId').prop('checked', false);

    });

    $('#button').click(function () {

        console.log("button");
        $('#myTable tr').each(function () {

            console.log("table");

            $(this).find('td input:checked').each(function () {

                container[counter] = $(this).val();
                counter++;
            });

            console.log("container: " + container);
        });

        $.ajax({
            type: "POST",
            url: '/AccountManagement/GetAccForRol',
            data: { 'myArray': container },
            success:
                alert("fdsfds")

        });

    });

})
</script>

I'm trying to mark items from a list through checkbox and send them to my controller. When something is checked it should be saved into an array that i created (container). When the button is clicked I want to pass this array to my controller, but it doesn't work.

Here is a test view:

@{
    ViewBag.Title = "Test";
}

<form name="frmTest" method="POST">
    @Html.Label("Your name Please")
    @Html.TextBox("username")
    <input class="btn btn-success btn-lg btn-block" type="submit" value="Login">
</form>

<script>
    $(function () {
        $("form[name='frmTest']").submit(function (e) {
            var stringArray = new Array();
            stringArray[0] = "item1";
            stringArray[1] = "item2";
            var postData = { Names: stringArray };
            $.ajax(
            {
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "AjaxTest",
                //dataType: "json",
                data: JSON.stringify(postData),
                success: function (data, status) {
                    alert("Pass" + data);
                },
                error: function (ex) {
                    alert("Fail" + ex);
                }
            });
            e.preventDefault();
        });
    });

</script>

Here is the controller:

public class AccountController : Controller
{
    public ActionResult Test()
    {
        return View();
    }
    public JsonResult AjaxTest(List<string> Names)
    {
        return Json("You posted: " +  Names.Count + " items.", JsonRequestBehavior.AllowGet);
    }
}

The Test action method returns the view, and when you click the button it submits the form (sends the array to the AjaxTest action).

The important part is to call JSON.stringify so jQuery leaves it alone since it is already JSON, and the ASP MVC engine will take care of the binding at the server level.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM