【问题标题】:Send complex JavaScript object to ASP.Net MVC Action将复杂的 JavaScript 对象发送到 ASP.Net MVC Action
【发布时间】:2009-12-31 20:30:54
【问题描述】:

这似乎是一个很常见的主题,一些人给出了一些非常有建设性的答案,但我仍在努力让我的尝试发挥作用。

问题与this one 非常相似,只是我只是尝试发送单个复杂对象而不是数组。

我的控制器如下所示:

[AcceptVerbs (HttpVerbs.Put)]
[Authorize]
[JsonFilter(Param="Designer", JsonDataType=typeof(Designer))]
public JsonResult 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);
}

检索页面数据并发布它的代码如下所示:

    $('#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);
            }
        });
    });

对象正在正确创建并发布到服务器(顺便说一下,我尝试过使用 POST 和 PUT),服务器似乎正在接收对象实例,但属性 - 像往常一样 - 全部为空。

我错过了什么?我已经尝试使用上面链接的示例问题中的方法(改编),但似乎仍然没有更接近解决方案。任何帮助表示赞赏。

【问题讨论】:

  • 这个 JsonFilter 动作过滤器属性是什么? (它绝对不是 ASP.NET MVC 本身的一部分。)我猜出于某种原因它不理解输入的 JSON 数据。
  • 啊 - 哎呀,忘了删除它。如果您查看我链接到的其他示例帖子,您会看到对自定义过滤器的引用,该过滤器应该有助于模型绑定。忽略它。
  • 找到了。我猜您发布的数据与该过滤器的设计不兼容。你能在过滤器的反序列化逻辑中设置一个断点,看看发生了什么吗?也就是说,反序列化器看到了什么,为什么它不能创建你的对象?
  • 事实证明非常接近。我没有检查以确保我设置的过滤器参数类型是正确的。我将在下面的答案中解释。

标签: javascript jquery asp.net-mvc ajax json


【解决方案1】:

事实证明,ActionResult 方法本身没有任何问题,JavaScript 对象或 Ajax 帖子也没有任何问题。问题实际上在于装饰 ActionResult 的自定义过滤器以及为其参数值设置的参数。

以下属性有一个“Designer”参数,用于我尝试传入的参数名称。我已将其作为参数名称和类型提供。

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

正确的版本应该是:

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

【讨论】:

    猜你喜欢
    • 2015-08-29
    • 1970-01-01
    • 2014-10-20
    • 1970-01-01
    • 2018-02-20
    • 1970-01-01
    • 1970-01-01
    • 2013-02-25
    • 1970-01-01
    相关资源
    最近更新 更多