简体   繁体   English

使用JavaScript将数据从视图返回到MVC中的控制器

[英]Return data using JavaScript from view to controller in MVC

I have WCF service that should be consumed by a MVC app. 我有WCF服务,应该由MVC应用程序使用。 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. 当我在控制器中接收数据时,第一个调用的WCF方法(findAccRoleMapp)应该在表中找到所有数据,然后调用另一个WCF方法(removeAccForRole)删除该数据。

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: 这是我认为的JS:

    <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). Test操作方法将返回视图,当您单击按钮时,它将提交表单(将数组发送到AjaxTest操作)。

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. 重要的部分是调用JSON.stringify,因此jQuery可以将其保留下来,因为它已经是JSON,并且ASP MVC引擎将在服务器级别处理绑定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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