【问题标题】:Get variables from ajax request in code behind在后面的代码中从 ajax 请求中获取变量
【发布时间】:2017-11-24 12:23:38
【问题描述】:

所以,前段时间,我需要发出 ajax 请求来访问后面的代码。我做到了 (here)。

但现在我正在使用 asp.NET Core 2.0,它的工作方式有所不同。好吧,现在我可以提出请求,但由于某种原因,变量为空(仅在后面的代码中,在客户端它们有内容。可能没什么大不了的,但我不明白为什么。

所以,这是我的 ajax 函数:

function Ajax(expression1, expression2, url, json, error) {
            console.log(expression1+" - "+ expression2);
            var request = { email: expression1, password: expression2 }

    $.ajax({
        url: url,
        method: 'post',
        contentType: 'application/json',
        data: JSON.stringify(request),
        dataType: 'json',
        success: function (resp) {
            console.log(request);
            if (expression1 === null || expression2===null)
                window.location.href = resp[json];
            else
                document.getElementById(error).innerHTML = resp[json];
        },
        error: function (error) {
        }
    })
}

还有c#代码:

public string ExternalLogin(string email, string name)
        {
            //TODO: Facebook login

            // Redirect link example. Could be another one.
            return "{\"facebook\":\"Home/About\"}";
        }

ajax 函数发出请求并触发 c# 函数,并返回我要求的内容。唯一的问题是空变量。为什么会这样?

编辑:请求的用户类:

public class User
    {
        [JsonProperty(PropertyName ="email")]
        public string Email { get; set; }
        [JsonProperty(PropertyName = "name")]
        public string Name { get; set; }
        [JsonProperty(PropertyName = "password")]
        public string Password { get; set; }
    }

【问题讨论】:

    标签: c# ajax asp.net-core-2.0


    【解决方案1】:

    参数绑定失败,因为您在此处发出 post 请求。 您必须将[FromBody] 属性添加到您的参数中。

    您可以在此处获取有关参数绑定的更多信息:

    编辑:

    您还将对象作为参数传递,因此您要么必须将路由参数更改为包含电子邮件和密码属性的对象,要么将 Content-Type 更改为 'application/x-www-form-urlencoded' 并传递查询字符串,例如 'email=....&password=....'

    【讨论】:

    • 仅此而已?我已经添加了 [FromBody] 标签,但它仍然不会收到任何值。
    • 所以,我按照建议创建了对象并且它工作正常。但现在我有一个跟进。我也有密码属性。并且以某种方式将名称反序列化为密码字段。这很奇怪。我什至在用户类中添加了标签 (?) [JsonProperty("name")] 让它知道它应该在哪里,但它保持不变......
    • 能否请您提供用户类?
    • 您是否尝试将“名称”属性添加到您的请求对象?
    • 哦,我明白了。我在这里粘贴了错误的 ajax 函数。这用于应用程序登录,因此密码,另一个有一个名称字段。但它基本上是一样的,除了这个有 5 个 args 而另一个有 4 个。但我仍然用 4 个 args 调用函数,它仍然会跳转到有 5 个 args 的那个。奇怪...
    猜你喜欢
    • 2018-06-26
    • 1970-01-01
    • 2021-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多