MVC5:通过 Ajax 发布 JSON 时未正确将数据传递到控制器

MVC5: Posting JSON via Ajax not correctly passing data to Controller?

本文关键字:数据 控制器 通过 Ajax 发布 JSON MVC5      更新时间:2023-09-26

我正在尝试在我的MVC5/EF Code-First应用程序中进行一些重复检查。在我的Create()资产视图中,我显示/隐藏用于通过 JS 输入新location_dept/location_room的文本框:

<div class="form-group">
        @*@Html.LabelFor(model => model.Location_Id, "Location_Id", htmlAttributes: new { @class = "control-label col-md-2" })*@
        <span class="control-label col-md-2">Location:</span>
        <div class="col-md-4">
            @*@Html.DropDownList("Location_Id", null, htmlAttributes: new { @class = "form-control dropdown" })*@
            @Html.DropDownListFor(model => model.Location_Id, (SelectList)ViewBag.Model_List, htmlAttributes: new { @class = "form-control dropdown", @id = "selectLocation" })
            @Html.ValidationMessageFor(model => model.Location_Id, "", new { @class = "text-danger" })
        </div>
        <div class="col-md-2">
            <div class="btn-group">
                <button id="createNewLocation" type="button" class="btn btn-success" aria-expanded="false">CREATE NEW</button>
            </div>
        </div>
        <div class="col-md-4">
            <div id="createLocationFormContainer" style="display:none">
                <form action="/createNewLocation">
                    <input type="text" id="textNewLocationDept" name="location_dept" placeholder="New Department" />
                    <input type="button" id="submitNewLocation" value="Submit" />
                    <input type="button" id="cancelNewLocation" value="Cancel" /><br />
                    <input type="text" id="textNewLocationRoom" name="location_room" placeholder="New Room" />
                </form>
            </div>
        </div>
    </div>

JS:

$('#createNewLocation').click(function () {
            $('#createLocationFormContainer').show();
        })
        $('#cancelNewLocation').click(function () {
            $('#createLocationFormContainer').hide();
        })
        $('#submitNewLocation').click(function () {
            var form = $(this).closest('form');
            var data = { location_dept: document.getElementById('textNewLocationDept').value, location_room: document.getElementById('textNewLocationRoom').value };
            // CORRECTLY SHOWING
            alert("Dept: " + data.location_dept + " | Room: " + data.location_room);
            $.ajax({
                type: "POST",
                dataType: "JSON",
                url: '@Url.Action("createNewLocation", "INV_Assets")',
                data: data,
                success: function (resp) {
                    if (resp.LocationRoomExists)
                    {
                        alert("Room Location [" + resp.Text + "] already exists. Please select from the DropDown.");
                    } else {
                        // FALSE
                        alert("LocationRoomExists: " + resp.LocationRoomExists);
                        // `undefined` returned for both values
                        alert("Department: " + resp.location_dept + " | Room: " + resp.location_room);
                        $ $('#selectLocation').append($('<option></option>').val(resp.ID).text(resp.LocDept + "| " + resp.LocRoom));
                        $('#createLocationFormContainer').hide();
                        var count = $('#selectLocation option').size();
                        $("#selectLocation").prop('selectedIndex', count - 1);
                    }
                },
                error: function () {
                    alert("ERROR - Something went wrong adding new Room Location [" + resp.Text + "]!");
                    $('#createLocationFormContainer').hide();
                }
            });
        });

然后,我使用控制器操作的 JSON POST来创建新INV_Location

    [HttpPost]
    public JsonResult createNewLocation(string department, string room)
    {
        INV_Locations location = new INV_Locations()
        {
            // ID auto-set during save.
            location_dept = department,
            location_room = room,
            created_date = DateTime.Now,
            created_by = System.Environment.UserName
        };
        var duplicateLocation = db.INV_Locations.FirstOrDefault(x => x.location_room.ToUpper() == location.location_room.ToUpper());
        try
        {
            if (duplicateLocation == null)
            {
                if (ModelState.IsValid)
                {
                    db.INV_Locations.Add(location);
                    db.SaveChanges();
                }
            }
            else
            {
                location = duplicateLocation;
            }
        }
        catch (Exception ex)
        {
            Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
        }
        return Json(new { ID = location.Id, LocDept = location.location_dept, LocRoom = location.location_room, LocationRoomExists = (duplicateLocation != null) }, JsonRequestBehavior.AllowGet);
    }

当我一起运行代码时,我在undefined|undefined下拉列表中得到一个结果。经过一些调试,我确定我的控制器没有收到department/room值(null)。

任何人都可以发现我对控制器的 AJAX 调用可能出了什么问题吗?

编辑

$('#selectLocation').append($('<option></option>').val(resp.ID).text(resp.LocDept + "| " + resp.LocRoom));

您需要确保参数与要发送的参数匹配:

var data = { department: document.getElementById('textNewLocationDept').value, room: document.getElementById('textNewLocationRoom').value };

您还需要匹配从控制器返回的数据。

您的操作将返回以下内容:

new { ID = location.Id, LocDept = location.location_dept, 
      LocRoom = location.location_room, 
      LocationRoomExists = (duplicateLocation != null) }

因此,您的绑定需要匹配属性,即

$('#selectLocation').append($('<option></option>')
   .val(resp.Id).text(resp.LocRoom   + "| " + resp.LocDept ));