繁体   English   中英

使用jquery创建一个列表并将其发布到asp.net mvc

[英]Create a list with jquery and post it to asp.net mvc

我正在寻找一种方法将给定类的所有现有复选框的值存储到某种列表或数组中,并通过jquery将结果发送到asp.net mvc控制器。 不必检查复选框,我需要所有这些复选框。

更多细节:

我的复选框看起来像这样

<input type="checkbox" value="1" class="a-checkbox"
<input type="checkbox" value="2" class="a-checkbox"
<input type="checkbox" value="3" class="a-checkbox"

如果我的MVC控制器看起来像这样会很好

public JsonResult SaveList(List<String> values) { //... }

我知道我可以通过以下方式访问复选框

 $('input.a-checkbox').each(
    function () {
        // create the list with the help of $(this).val()
    }
 );

 // jquery post would happen here

但我不知道如何创建这样的数据结构。 你可以帮帮我吗?

谢谢

编辑:很好,谢谢。 你能告诉我这有什么问题吗? 我的控制器确实被调用,但列表为空(在服务器端)

var list = [];
            $('a-checkbox').each(
                function () {
                    list.push($(this).val());
                }
            );

            $.ajax({
                type: "POST",
                url: myUrl,
                data: list,
                success: function (data) {
                    alert(data.Result);
                },
                dataType: "json",
                traditional: true
            });

这会将所有checkbox值( value属性)放入一个Array

var values = [];
$(".a-checkbox").each(function () {
    values.push($(this).val());
});

// values now equals ["1", "2", "3"]

试试这个

var list = [];
$('input.a-checkbox').each(
    function () {
        // create the list with the help of $(this).val()
        list.push($(this).val());
    }
);

现在您可以将list对象发布到您的mvc控制器操作。

我使用.Serialize()来格式化我的mvc ajax动作的表单数据。

var checkPostData = $(".a-checkbox").serialize();

http://api.jquery.com/serialize/

我在MVC模式下遇到了同样的问题Nulls。 我发现使用$(“input:checked”)作为我的数据,而不是尝试将值提取到js中的数组更好地工作,我通过给出复选框名称值来修复Nulls问题,因为MVC绑定了输入名称。

HTML

<a class="post-checkboxes" href="#">post checkboxes</a>
<input name="[MVC viewmodel list variable name]" type="checkbox" value="1" />
<input name="[MVC viewmodel list variable name]" type="checkbox" value="2" />

使用Javascript

$('.post-checkboxes').click(function (e) {
    e.preventDefault();
    $.post("[location to post to]", $("input:checked"));            
});

暂无
暂无

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

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