MVC5:通过 Ajax 发布 JSON 时未正确将数据传递到控制器
MVC5: Posting JSON via Ajax not correctly passing data to Controller?
我正在尝试在我的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 ));
相关文章:
- 在控制器和数据对象之间同步数据
- 将不在模型中的数据返回到mvc控制器
- 通过连线将数据从js发送到控制器
- ng绑定和ng href问题.ng href未从控制器加载数据
- 尝试从控制器加载带有json数据的Simile时间线
- 如何将角度输入指令数据传递给控制器
- 使用服务(AngularJS)在控制器之间共享数据
- 模型数据未通过窗体传播到控制器ASP.NET MVC4
- 从控制器返回到Ajax的数据混乱
- 通过共享服务在两个不同ng应用程序中的控制器之间共享数据
- 使用2个控制器管理工厂JSON$http数据
- 使用Angularjs在两个不同页面的控制器之间共享数据
- 将工厂服务数据发送到控制器,以便在视图中使用
- 2ng控制器,并且需要在控制器之间共享数据
- 如何正确地将数据从自定义服务传递到角度控制器
- 在控制器angular js之间共享数据
- 将数据从Javascript传递到Laravel控制器
- JQuery$.ajax()发布数据以调用我的控制器中的方法
- 如何将json文件中的数据提取到对象数组中,并在两个控制器之间共享
- 如何使用ajax调用获取数组列表数据(将数组列表数据控制器传递给ajax方法)