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

Javascript MVC5:通过Ajax发布JSON没有正确地将数据传递给控制器?,javascript,jquery,ajax,json,asp.net-mvc,Javascript,Jquery,Ajax,Json,Asp.net Mvc,我试图在我的MVC5/EF代码第一个应用程序中执行一些重复检查。在我的Create() <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-m

我试图在我的MVC5/EF代码第一个应用程序中执行一些重复检查。在我的
Create()

<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>
当我一起运行代码时,我会在下拉列表中得到一个结果
undefined | undefined
。经过一些调试后,我确定我的控制器没有接收到
部门
/
房间
值(
null

有人能发现我对控制器的AJAX调用可能出了什么问题吗

编辑

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

$('#selectLocation')。追加($('').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 ));
$('#selectLocation')。追加($('')
.val(resp.Id).text(resp.LocRoom+“|”+resp.LocDept));

看起来您的表单实际上是在提交,而不是通过AJAX访问控制器。研究如何防止违约事件。如果它是通过AJAX提交的,请尝试更改
数据
对象中的变量名,以匹配action方法中的参数。感谢hutchonoid,我自己刚刚发现了这一点。不幸的是,这不是问题的根源。当我进入
Dept:IT | Room:Storage
(一个数据库中已经存在的值,我的控制器代码不标记重复,一直到
db.SaveChanges()
其中一个
异常捕获:
System.Data.Entity.Validation.DbEntityValidationException对一个或多个实体的验证失败。有关详细信息,请参阅“EntityValidationErrors”属性。
@AnalyticLunatic也可以看到第一次更新,即数据参数。谢谢!就是这样(似乎我以前遇到过这个问题,但这次忽略了)。我知道这是一个稍微无关的便笺,但是你知道当视图加载时如何在我的下拉列表中显示
Dept | Room
吗?这两个字段位于我的
INV_Locations
表中,目前我只是通过
ViewBag
ViewBag.Location\u Id=new SelectList将
Room
传递到列表中(db.INV_Locations,“Id”,“location_room”)
@AnalyticLunatic嗨,抱歉,刚刚看到你的上述评论。试试这个
ViewBag.location_Id=new SelectList(从db.INV_Locations.ToList(){new{Id=l.Id,dep_room=l.location_dep+“|”+l.location_room},“Id”,“dep_room”)
:)@AnalyticLunatic抱歉,我没有测试项目设置来测试它。这里看起来是一样的:
$('#selectLocation').append($('<option></option>')
   .val(resp.Id).text(resp.LocRoom   + "| " + resp.LocDept ));