MVC5:通过Ajax发布JSON不正确地将数据传递给控制器?

时间:2022-03-23 21:33:39

I am attempting to do some duplication checking in my MVC5/EF Code-First application. On my Create() Asset View, I show/hide textboxes for entering a new location_dept/location_room via JS:

我正在尝试在我的MVC5/EF代码优先应用程序中进行一些重复检查。在我的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:

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

I then use a JSON POST to my controller action to create the new INV_Location:

然后,我使用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);
    }

When I run the code all together, I get a result in my dropdown of undefined|undefined. After some debugging I determined that my controller is not receiving a department/room value (null).

当我一起运行这些代码时,会得到未定义|的下拉结果。经过一些调试,我确定我的控制器没有接收到一个部门/房间值(null)。

Can anyone spot what might be going wrong with my AJAX call to my controller?

谁能指出我对控制器的AJAX调用有什么问题吗?

EDIT:

编辑:

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

(“# selectLocation”).append(美元(“ <选项> < /选项>”).val(resp.ID)。text(分别地。);

1 个解决方案

#1


1  

You need to make sure your parameters match that you are sending:

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

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

You also need to match the data that you are returning from your controller.

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

Your action returns this:

你的行动回报:

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

So your bind needs to match the properties i.e.

所以绑定需要匹配属性。

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

#1


1  

You need to make sure your parameters match that you are sending:

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

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

You also need to match the data that you are returning from your controller.

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

Your action returns this:

你的行动回报:

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

So your bind needs to match the properties i.e.

所以绑定需要匹配属性。

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