c# - ASP.net MVC 和 jQuery 将多个表单序列化为对象列表并提交

标签 c# jquery asp.net-mvc asp.net-mvc-3

使用 asp.net mvc3 和 jquery

我在一个页面上有 x 个表单,每个表单都是在用户添加新项目时创建的。每个表单代表一个 c# 模型。每个表单都有一个字符串列表作为属性之一。我想要一个提交所有表单的保存所有按钮,但我想在我这样做之前将它们序列化到一个对象列表中,然后在后端进行排序。我如何使用 jQuery 做到这一点?

<form>
    <input name="ListThing" value="one" />
    <input name="ListThing" value="two" />
    <input name="ListThing" value="three" />
    <input name="Name" value="Bob" />
</form>

<form>
    <input name="ListThing" value="one" />
    <input name="ListThing" value="two" />
    <input name="ListThing" value="three" />
    <input name="Name" value="Pat" />
</form>

c#

public class myModel{
    public List<string> ListThing {get; set;}
    public string Name {get; set;}
}

Controller - 上传 Controller - Action

[HttpPost]
public ActionResult SaveAll( List<myModel> myModels )
{
    // do stuff
    return View();
}

最佳答案

不能有多个具有相同 ID 的元素。因此,首先修复您的标记:

<form>
    <input name="ListThing" value="one" />
    <input name="ListThing" value="two" />
    <input name="ListThing" value="three" />
    <input name="Name" value="Bob" />
</form>

<form>
    <input name="ListThing" value="one" />
    <input name="ListThing" value="two" />
    <input name="ListThing" value="three" />
    <input name="Name" value="Pat" />
</form>

然后假设您有一些链接来触发操作:

@Html.ActionLink("Save all", "SaveAll", "Home", null, new { id = "saveall" })

您可以简单地将其 AJAX 化:

$('#saveall').click(function () {
    var data = $('form').map(function () {
        var $form = $(this);
        return {
            name: $form.find(':input[name=Name]').val(),
            listThing: $form.find(':input[name=ListThing]').map(function () {
                return $(this).val();
            }).toArray()
        };
    }).toArray();

    $.ajax({
        url: this.href,
        type: 'post',
        contentType: 'application/json',
        data: JSON.stringify({ myModels: data }),
        success: function (result) {
            alert('done');
        }
    });

    return false;
});

关于c# - ASP.net MVC 和 jQuery 将多个表单序列化为对象列表并提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5502675/

相关文章:

c# - 同时从多个线程在 NetworkStream 上使用 WriteAsync 是否线程安全?

c# - 你如何在 C# WPF 中的 DataGrid 标题之间放置垂直线

javascript - 键盘 "Swipe"JavaScript 事件

jquery - jqGrid:具有全局搜索的多词搜索

c# - 向用户报告异常消息时的最佳实践

c# - 表单例份验证 cookie 中的 ASP.NET MVC 用户数据与添加到 session

c# - 在 MVC5 中使用 Html.DisplayFor() 的日期格式

c# - 显示 DataTable 的值

c# - 披萨、线程、等待、通知。这是什么意思?

javascript - 在 css3 表单上使用 Javascript