【问题标题】:ASP.NET MVC ModelBinding with $ajax vs $post and using KnockoutASP.NET MVC ModelBinding 与 $ajax 与 $post 并使用 Knockout
【发布时间】:2014-01-24 09:43:33
【问题描述】:

好的,我找不到任何与我的确切问题有关的东西,所以希望有人能帮我补充一下。我正在使用 ASP.NET MVC 4(针对 4.5.1 Fx)并使用 KO 3.0 和最新的 jQuery。我有一个 KO 模型,它比它所代表的 .NET 模型具有更多的属性(2 个计算的 observables 只需要在视图中而不是在后端)。场景是用户进行了一些更改并点击了保存按钮。这会调用 KO VM 中的一个方法,该方法使用 jQuery 回发到服务器并保存更改。 Controller 方法如下所示:

public void Post(Profile profile)
    {
        var modifiedDate = DateTime.UtcNow;
        var existingProfile = db.Profiles.FirstOrDefault(x => x.Id == profile.Id);

        ...     

        db.SaveChanges();

    }

我的 KO 方法如下所示:

self.updateProfile = function (profile) {
    $.post("/api/profile", profile, function () {
        alert('saved');
    });
};

现在这工作得很好,但是如果我尝试更改为使用 $ajax 方法(这是我想要更精细控制的方法),它会失败。

    $.ajax({
        url: "/api/profile",
        type: "post",
        dataType: "json",
        data: {
            profile: profile
        },
        success: function () {
            alert('saved');
        }
    });

Controller 方法中的对象配置文件未绑定到 $ajax 方法发送的数据。我不知道为什么,因为 $post 只是 $ajax 的高级抽象。任何帮助将不胜感激。

【问题讨论】:

  • 打开调试控制台,这两个请求头有何不同?
  • 查看现在在 Fiddler 4 中使用 WebForms Inspector 的 2 个不同请求,我看到 $post 方法具有值 Id:value、OwnerId:value 等,而 $ajax 方法具有profile[Id]:值,profile[OwnerId]:值。很明显,这就是问题所在。我需要在 $ajax 中复制的 $post 方法有什么作用?

标签: asp.net-mvc jquery knockout.js asp.net-web-api


【解决方案1】:

data: {profile: profile}, 是两个 sn-ps 不同的地方。你可能想要data: profile

它们在此处也有所不同:dataType: "json",但如果您的服务器返回 json,那也没关系。

$.ajax({
    url: "/api/profile",
    type: "post",
    //dataType: "json", optional, you can keep it if you want.
    data: profile,
    success: function () {
        alert('saved');
    }
});

【讨论】:

  • 谢谢!我习惯于发布多个参数,只是认为 {} 和命名参数是必需的。
  • 另外,作为一小段信息,您可以在$.post 中复制dataType: "json" 并添加一个参数:$.post(url,data,successHandler,"json")
  • 嗨,知道如何使用 $.ajax 传递多个参数吗?我在下面尝试但徒劳 - $.ajax({ url: "/api/profile", type: "post", //dataType: "json", optional, 你可以保留它,如果你愿意。data: { param1: profile1, param2: profile2} 成功: function () { alert('saved'); } });
  • 发现非常好的文章。 weblog.west-wind.com/posts/2012/May/08/… 这解释了如何将多个复杂对象传递给 MVC 控制器。
猜你喜欢
  • 2013-07-05
  • 1970-01-01
  • 2019-09-21
  • 2018-12-11
  • 1970-01-01
  • 1970-01-01
  • 2010-10-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多