Search code examples
ajaxasp.net-mvcjsonresult

MVC JsonResult, can't return an object, property always ends up null


I have the following MVC Action:

[HttpPost]
    public JsonResult Save(Guid? id, LabSaveModel labSaveModel)
    {
        labSaveModel = id == null ? Create(labSaveModel) : Update((Guid) id, labSaveModel);
        _labService.SetActionMessage(labSaveModel, true);

        return Json(new JsonLabModel(){ CreateAnother = labSaveModel.CreateAnother, ReturnUrl = labSaveModel.ReturnUrl}, JsonRequestBehavior.DenyGet);
    }

And the following AJAX:

$.ajax({
            url: '@Url.Action("Save", "Labs")',
            type: 'POST',
            data: mappedModel.dataToPost(),
            dataType: "json",
            contentType: 'application/json; charset=utf-8',
            success: function(data) {
                   //do stuff
            }
 });

But every time I check data on success method, ReturnUrl is null. Despite when debugging the value is not null. It returns this:

{"CreateAnother":false,"ReturnUrl":null}

Strangely enough, if I change the CreateAnother value to true, that works and passes true fine, but ReturnUrl is still null, and I confirm on the post itself the data is there and not null.

What is going on?


Solution

  • I think it has to do with the fact that ReturnUrl parameter name has a special treatment in the ASP.NET request handling pipeline. See more in this thread.

    As a simple resolution, I would suggest renaming this parameter to ReturnLink or similar, and that should do it.