我正在将 json 对象传递给 asp.net mvc 控制器操作。这两个参数均为空。
有人可以发现错误的命名错误吗?
/* Source Unit */
var sourceParent = sourceNode.getParent();
var sourceUnitParentId = sourceParent == null ? null : sourceParent.data.key;
var sourceUnit = { unitId: sourceNode.data.key, parentId: sourceUnitParentId };
var sourceUnitJson = JSON.stringify(sourceUnit);
/* Target Unit */
var targetParent = targetNode.getParent();
var targetUnitParentId = targetParent == null ? null : targetParent.data.key;
var targetUnit = { unitId: targetNode.data.key, parentId: targetUnitParentId };
var targetUnitJson = JSON.stringify(targetUnit);
moveUnit(sourceUnitJson, targetUnitJson);
function moveUnit(sourceUnit, targetUnit) {
$.ajax({
url: '@Url.Action("Move", "Unit")',
type: 'POST',
data: { sourceUnit: sourceUnit, targetUnit: targetUnit },
success: function (response) {
},
error: function (e) {
}
});
}
[HttpPost]
public ActionResult Move(DragDropUnitViewModel sourceUnit, DragDropUnitViewModel targetUnit)
{
Unit sUnit = Mapper.Map<DragDropUnitViewModel, Unit>(sourceUnit);
Unit tUnit = Mapper.Map<DragDropUnitViewModel, Unit>(targetUnit);
_unitService.MoveUnit(sUnit, tUnit);
return new EmptyResult();
}
为什么不使用视图模型?如果要将 JSON 传递给控制器操作,请定义包含 2 个属性的视图模型,然后JSON.stringify
整个请求。
下面是视图模型:
public class MoveViewModel
{
public DragDropUnitViewModel SourceUnit { get; set; }
public DragDropUnitViewModel TargetUnit { get; set; }
}
现在,控制器操作将视图模型作为参数:
[HttpPost]
public ActionResult Move(MoveViewModel model)
{
Unit sUnit = Mapper.Map<DragDropUnitViewModel, Unit>(model.SourceUnit);
Unit tUnit = Mapper.Map<DragDropUnitViewModel, Unit>(model.TargetUnit);
_unitService.MoveUnit(sUnit, tUnit);
return new EmptyResult();
}
最后使用 AJAX 调用此控制器操作并通过确保您指定了正确的请求内容类型来发送 JSON 请求,否则 MVC ASP.NET 不知道如何反序列化 JSON 请求:
/* Source Unit */
var sourceParent = sourceNode.getParent();
var sourceUnitParentId = sourceParent == null ? null : sourceParent.data.key;
var sourceUnit = { unitId: sourceNode.data.key, parentId: sourceUnitParentId };
/* Target Unit */
var targetParent = targetNode.getParent();
var targetUnitParentId = targetParent == null ? null : targetParent.data.key;
var targetUnit = { unitId: targetNode.data.key, parentId: targetUnitParentId };
/* build the view model */
var moveModel = { sourceUnit: sourceUnit, targetUnit: targetUnit };
/* Pass the view model to the server using an AJAX request */
moveUnit(moveModel);
function moveUnit(moveModel) {
$.ajax({
url: '@Url.Action("Move", "Unit")',
type: 'POST',
// It's very important to specify the correct content type
// request header because we are sending a JSON request
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(moveModel),
success: function (response) {
},
error: function (e) {
}
});
}
总结:
- 每次您的控制器操作采用多个参数时,您都做错了。立即停止并定义视图模型。
- 每次控制器操作将域模型传递给视图时,您都做错了。立即停止并定义视图模型。
如您所见,这一切都与MVC ASP.NET 视图模型有关。