开发者

Send complex JavaScript object to ASP.Net MVC Action

开发者 https://www.devze.com 2022-12-15 08:57 出处:网络
This seems to be quite a common theme and a few people have given some very constructive answers, but I\'m still struggling to get my attempt to work.

This seems to be quite a common theme and a few people have given some very constructive answers, but I'm still struggling to get my attempt to work.

The problem is much the same as this one for example, except that I'm only trying to send a single complex object instead of an array.

My controller looks like this:

[AcceptVerbs (HttpVerbs.Put)]
[Authorize]
[JsonFilter(Param="Designer", JsonDataType=typeof(Designer))]
public Jso开发者_Go百科nResult SaveProfile(Designer Profile)
{
    ProfileRepository Repo = new ProfileRepository();

    Designer d = Repo.GetById(Profile.ID);
    d.Comments = Profile.Comments;
    d.DisplayName = Profile.DisplayName;
    d.Email = Profile.Email;
    d.FirstName = Profile.FirstName;
    d.LastName = Profile.LastName;


    Repo.Update(d);

    return Json(Profile);
}

The code for retrieving the page data and posting it looks like this:

    $('#save-profile').click(function () {

        var Profile = {};
        var context = $('#profile-data')[0];

        $('span', context).each(function () {
            Profile[this.id] = $(this).text();
        });

        Profile.ID = $('h3', context).attr('id');
        console.log(Profile);

        //var DTO = { 'Profile': Profile };

        $.ajax({
            type: "PUT",
            url: "/Home/SaveProfile",
            data: { 'Profile': Profile },
            success: function (data) {
                console.log(data);
            }
        });
    });

The object is being correctly created and posted to the server (I've tried using POST and PUT, by the way), the server appears to be receiving an object instance, but the properties are - as usual - all null.

What am I missing? I've tried using the approach (adapted) from the example question linked above, but still don't seem to be getting any closer to the solution. Any help appreciated.


As it turns out, there's nothing wrong with the ActionResult method itself and neither is there any issue with the JavaScript object or Ajax post. The problem actually lies in the custom filter that decorates the ActionResult and the parameter being set for its param value.

The following attribute has a parameter of "Designer" set for the name of the parameter I'm trying to pass in. I've supplied this as both the parameter name and the type.

[JsonFilter(Param="Designer", JsonDataType=typeof(Designer))]

The correct version should be:

[JsonFilter(Param="Profile", JsonDataType=typeof(Designer))]
0

精彩评论

暂无评论...
验证码 换一张
取 消