带有来自可变数量输入框的ajax的jQuery帖子

时间:2014-11-02 21:23:02

标签: javascript c# jquery ajax asp.net-mvc

我正在尝试使用带有ajax的jQuery post将两个不同字段的可变数量的输入的用户输入传递回控制器。我遇到的问题不仅仅是第一次投入。例如,如果为员工分配了多件设备,则只将第一件设备传递给控制器​​。

在视图中,我在一个表格中显示每个员工,每个员工都有一个按钮,用于打开可以分配其各个设备的模式。在每个模态中有两个文本框(车辆和工具),用户可以选择使用jQuery添加更多文本框。

我是JS的新手,无法弄清楚如何确定有多少输入,我也不知道如何将这些输入放入数组传递给控制器​​。非常感谢任何帮助!

查看:

@int count = 0;

@foreach (var item in Model)
{
    <tr>
        <td>
            <button class="btn btn-default" data-toggle="modal" data-target="#modal-@count">
                Assign Resources
            </button>

            <div class="modal fade" id="modal-@count" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
                <div class="modal-dialog modal-lg">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                            <h4 class="modal-title" id="myModalLabel">@item.Rank @item.FirstName @item.LastName</h4>
                        </div>
                        <div class="modal-body">
                            <input type="hidden" value="@item.assignedRosterID" id="assignedRosterID-@count" />
                            <div class="table">

                                <table>
                                    <thead>
                                        <tr>
                                            <th class="text-center">
                                                Vehicles
                                            </th>

                                            <th class="text-center">
                                                Equipment
                                            </th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr>
                                            <td valign="middle">
                                                <div class=”addV” id=”addV-@count”>
                                                    <p>
                                                        <input type="text" size="20" class="text-center" value="" id="vehicleNumber-@count" name=”vehicle” placeholder="Vehicle Number" /> &nbsp;
                                                    </p>
                                                </div>
                                            </td>

                                            <td valign="middle">
                                                <div class="addEquip" id="addEquip-@count">
                                                    <p>
                                                        <input type="text" id="equipmentLabel-@count" size="20" class="text-center" name="equipment" value="" placeholder="Equipment Label" />&nbsp;
                                                    </p>
                                                </div>
                                            </td>

                                        </tr>
                                        <tr>
                                            <td></td>
                                            <td>
                                                <a href="#" class="addVehicle" id="addVehicle-@count"> Add Additional Vehicle</a>
                                            </td>
                                            <td>
                                                <a href="#" class="addEquipment" id="addEquipment-@count"> Add Additional Equipment</a>

                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                                <span style="color: red"></span>
                            </div>
                            <div>

                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-default" data-dismiss="modal" id="closeModal-@count">Close</button>
                            <button type="button" class="btn btn-primary" id="saveModal-@count">Save changes</button>
                        </div>
                    </div>
                </div>
            </div>
        </td>


        <td style="font-weight:bold">
            @Html.DisplayFor(modelItem => item.LastName)
        </td>
        <td style="font-weight:bold">
            @Html.DisplayFor(modelItem => item.FirstName)
        </td>
    </tr>
    count++;
}

JS

for (var i = 0; i < $('#count').val() ; i++) {
(function (i) {
    i
    $('#saveModal-' + i).click(function () {


        var DetailsVM = {
            arID: $('#assignedRosterID-' + i).val(),
            vehicleNumber: $('#vehicleNumber-' + i).val(),
            equipmentLabel: $('#equipmentLabel-' + i).val()
        }

        $.ajax({
            type: 'POST',
            url: '/Rosters/SaveResources',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: JSON.stringify(DetailsVM),
            traditional: true,
            success: function (response) {
                alert("Data Inserted Successfully!");
            },
            error: function (xhr, err) { alert(xhr.responseText) }



        });
    });
})(i);
};



for (var i = 0; i < $('#count').val() ; i++) {
    (function (i) {
        $(function () {
            var addDiv = $('#addV-' + i);
            var j = $('#addV-' + i + 'p').size() + 1;


            $(document).on('click', '#addVehicle + i, function () {
                $('<p><input type="text" id="vehicle + i + '-' + j + '" size="20" name="vehicle + j + '" value="" placeholder=" Vehicle Number" /><a href="#" id="remNew"> Remove</a> </p>').appendTo(addDiv);
                j++;

                return false;
            });

            $(document).on('click', '#remNew', function () {
                if (j > 1) {
                    $(this).parents('p').remove();
                    j--;
                    //$("span").text("There are " + j + " equipment input boxes. ");
                }
                return false;
            });
        });

    })(i);
};



for (var i = 0; i < $('#count').val() ; i++) {
    (function (i) {
        $(function () {
            var addDiv = $('#addEquip-' + i);
            var j = $('#addEquip-' + i + 'p').size() + 1;


            $(document).on('click', '#addEquipment-' + i, function () {
                $('<p><input type="text" id="equipment-' + i + '-' + j + '" size="20" name="equipment_' + j + '" value="" placeholder=" Equipment Label " /><a href="#" id="remNew"> Remove</a> </p>').appendTo(addDiv);
                j++;

                return false;
            });

            $(document).on('click', '#remNew', function () {
                if (j > 1) {
                    $(this).parents('p').remove();
                    j--;
                    //$("span").text("There are " + j + " equipment input boxes. ");
                }
                return false;
            });
        });

    })(i);


  };

型号:

 public class DetailsVM
    {
        public string arID { get; set; }
        public string vehicleNumber { get; set; }
        public string equipmentLabel { get; set; }

}

此逻辑仅设置为保存每种类型中的一种,因为多个不起作用。当我在此处设置断点并检查VM时,它只包含第一个值。

控制器:

public ActionResult SaveResources(DetailsVM VM)
        {
            int assignedRosterID = Int32.Parse(VM.arID);
            int equipmentID = db.Equipments.Where(x => x.EquipmentLabel == VM.equipmentLabel).Select(x => x.EquipmentID).FirstOrDefault();
            int vehicleID = db.Vehicles.Where(x => x.VehicleNumber == VM.vehicleNumber).Select(x => x.VehicleID).FirstOrDefault();


        var tempEquipments = new TempEquipment();
        tempEquipments.AssignedRosterID = assignedRosterID;
        tempEquipments.EquipmentID = equipmentID;
        db.TempEquipments.Add(tempEquipments);

        var tempVehicles = new TempVehicle();
        tempVehicles.AssignedRosterID = assignedRosterID;
        tempVehicles.VehicleID = vehicleID;
        db.TempVehicles.Add(tempVehicles);


db.SaveChanges();


        return Json(1, JsonRequestBehavior.AllowGet);

    }

1 个答案:

答案 0 :(得分:1)

你可以在保存按钮上设置一个类,并通过
获取父tr var tr = $(this).closest('tr')
 所以... arID就像是  tr.find('[name="arID"]')
将第一个for包装在函数中并使其成为全局 要使其成为全局,请将其降低到for以上

function bindClick() {}

然后,由于按钮上的课程,您不需要for 在你的bindClick中你可以去

$('.saveModal').each(function( ){
    $(this).unbind('click').on('click, function(e){
        e.preventDefault(); // do this if you dont want to do default action for this button .. like to submit a form
        var tr = $(this).closest('tr') // get the parent of all inputs to search in this container
        [native code] // var DetailsVM = {...
    }
});

然后将$('#assignedRosterID-' + i).val()更改为tr.find('.assignedRosterID').val()
不要忘记在输入中添加类!或按属性名称查找它们:tr.find('[name="your-field-name"]').val()

对您的其他功能执行相同的操作,并在您的函数中触发bindClick,您可以在其中添加新字段;)