I am passing to json objects to an asp.net mvc controller action. Both parameters are null.
Can someone spot the error prolly wrong naming?
/* 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();
}
Why don’t you use a view model? If you want to pass JSON to a controller action then define a view model containing the 2 properties and then
JSON.stringifythe entire request.Here’s your view model:
Now your controller action will take the view model as argument:
and finally invoke this controller action using AJAX and send JSON request by making sure that you have specified the correct request content type, otherwise ASP.NET MVC wouldn’t know how to deserialize back the JSON request:
Summary:
As you can see it’s all about view models in ASP.NET MVC.