【问题标题】:Parameter to Web Service via Jquery Ajax Call通过 Jquery Ajax 调用向 Web 服务提供参数
【发布时间】:2012-07-30 07:26:10
【问题描述】:

我正在使用显示模块模式和淘汰赛来绑定表单。当以该表单(注册)输入数据时,需要将其回传到 MVC4 网络方法。

这里是 Jquery 代码

    /*
Requires JQuery
Requires Knockout
*/
op.TestCall = function () {

    // Private Area
    var _tmpl = { load: "Loading", form: "RegisterForm"};

    var
    title = ko.observable(null)
    template = ko.observable(_tmpl.load),
    msg = ko.observable(),

    postData = ko.observable(),

    PostRegistration = function () {
        console.log("Ajax Call Start");
        var test = GetPostData();
        $.ajax({

            type: "POST",
            url: obj.postURL, //Your URL here api/registration
            data: GetPostData(),
            dataType: "json",
            traditional: true,
            contentType: 'application/json; charset=utf-8'


        }).done(Success).fail(Failure);
        console.log("Ajax Call End");
    },
    GetPostData = function () {
        var postData = JSON.stringify({
            dummyText1: dummyText1(),
            dummyText2: dummyText2(),

        });
        return postData;

    }


    return {
        // Public Area
        title: title,
        template: template,
        dummyText1: dummyText1,
        dummyText2: dummyText2
    };
}();

控制器代码现在很简单

 // POST api/registration
    public void Post(string data)
    {

        ///TODO

    }

当我尝试捕获数据(使用简单的 console.log)并在 jslint.com 中验证它时,它是一个有效的 Json。

  1. 我尝试将数据硬编码为

    data: "{data: '{\'name\':\'niall\'}'}", 但在我的网络方法中,我仍然得到 null。

  2. 在我的 Post 方法中添加了标签 [System.Web.Script.Services.ScriptMethod(UseHttpGet = false, ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)],但仍然没有结果

  3. 甚至尝试过 JSON.Stringify data: JSON.stringify(data) 但我的网络方法仍然为空。

我无法找出解决方案。

在此链接中发现了类似问题 http://forums.asp.net/t/1555940.aspx/1 甚至Passing parameter to WebMethod with jQuery Ajax 但没有帮助我:(

【问题讨论】:

    标签: ajax asp.net-mvc-4 revealing-module-pattern


    【解决方案1】:

    MVC 和 WebApi 使用Model Binding 的概念。

    所以最简单的解决方案是,你需要创建一个与发送的 Json 数据的结构相匹配的 Model 类来接受服务器上的数据:

    public void Post(MyModel model)
    {
       ///TODO
    }
    
    public class MyModel
    {
       public string DummyText1 { get; set; }
    
       public string DummyText1 { get; set; }
    }
    

    注意:json 和 C# 属性名称应该匹配。

    【讨论】:

    • 我不能用这种方法做到这一点,我需要使用 JSON.stringify 并获得所需。我已经稍微更新了我的问题。谢谢你的回答。 :)
    【解决方案2】:

    只允许转义的双引号字符,而不是单引号,所以你只需要用双引号替换单引号:

    data: "{data: '{\"name\":\"niall\"}'}"
    

    或者如果你想使用 stringify 函数,你可以这样使用它:

    data: "{data: '" + JSON.stringify(data) + "'}"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多