MVC5:通过Ajax发布JSON没有正确地将数据传递给Controller?

时间:2015-03-17 15:30:36

标签: javascript jquery ajax json asp.net-mvc

我正在尝试在我的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));

1 个答案:

答案 0 :(得分:1)

您需要确保您的参数与您发送的参数相符:

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 ));