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

标签 javascript jquery ajax json asp.net-mvc

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

<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到我的 Controller Action 来创建新的 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 的下拉列表中得到一个结果.经过一些调试后,我确定我的 Controller 没有收到 department。/room值(null)。

谁能发现我对 Controller 的 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 };

您还需要匹配从 Controller 返回的数据。

你的操作返回这个:

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

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

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

关于javascript - MVC5 : Posting JSON via Ajax not correctly passing data to Controller?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29103188/

相关文章:

javascript - jQuery - jQGrid - 展开、折叠网格行上的子网格单击

c# - 如何从子页面触发更新面板回发?

javascript - 加载内容 AJAX Jquery - 需要如何将数据发送到加载的页面?

javascript - 将通用逻辑提取到 JavaScript 中的可重用函数中

jQuery 正则表达式验证 : unsigned integer or float (max 2 decimal), 只有点,没有逗号

jquery - 按钮与 HTML 中的可点击 Div

javascript - 如何让我的 ajax 方法正确有效的文本框?

javascript - 如何通过单击包含其他视频源的链接来获取视频源 [Java 脚本]

javascript - 跨节点和浏览器共享 nunjucks 过滤器

javascript - 错误: Not allowed to load local resource