简体   繁体   中英

Jquery post to mvc 4 controller not passing data

I'm trying to pass data from JQuery to an MVC 4 controller. The controller gets invoked, but no data is passed. In the past I always just used form serialization, but that's not appropriate here.

My Controller:

[HttpPost]
public ActionResult Write(VideoSessionEnvelope envelope)
{
    if (ModelState.IsValid)
    {
        envelope = Log.Write(envelope);
    }
    var result = Json(envelope);
    return result;
}

We use an envelope class as a container for all view models

public class VideoSessionEnvelope : BaseEnvelope
{
    public VideoSessionEnvelope()
    {
        SessionStart = new VideoSessionStartViewModel();
    }
    public Guid? LogEntryID { get; set; }
    public VideoSessionStartViewModel SessionStart { get; set; }
    }
}

The view model

public class VideoSessionStartViewModel: IViewModel
{
    public string SessionId { get; set; }
    public int UserId { get; set; }
    public string Message { get; set; }
}

And finally the javascript

var Logging = Logging || {};
Logging.VideoSession = function () {
    var Start = function (sessionId, userId, message) {
    var envelope = {
            SessionStart: {
                "SessionId": sessionId,
                "UserId": userId,
                "Message": message
            }
        }
        var data = JSON.stringify(envelope);
        $.ajax({
            type: "POST",
            url: "/Logging/Write",
            data: data,
            datatype: "application/json",
            success: function (result) {
                return result;
            },
            error: function (request, status, error) {
                return error;
            }
        });
    };

    return {
        Start: Start
    };
}();

According to Firebug the data is passed as

JSON
SessionStart  Object { SessionId="sessionIdVal", UserId=123, Message="messageValue"}
Message      "messageValue"
SessionId    "sessionIdVal"
UserId       123

The controller gets called, but the properties in the view model are always null. I've tried several variations on the theme, nothing seems to work.

Try wrapping your data in a literal with the name as envelope so it will be picked up by the Model Binder:

data: { envelope: data },

UPDATE

Remove the call to JSON.stringify() , it is not strictly necessary to serialize the object literal.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM