Ajax调用asp.net-变量始终为null

时间:2019-07-08 09:32:46

标签: c# asp.net ajax asp.net-ajax razor-pages

我无法使用Ajax将值传输到我的asp.net razorpage处理程序。 它始终在razorpage端接收空值。否则,它可以正常工作,而javascript不会没有错误地进行响应。

调用C#函数“ OnPost”,但始终将空值作为参数。

我在这里想念什么?我查看了很多示例,但无法说明。我是否缺少必须在项目中设置的内容?请让我知道我是否应该提供更多代码!

public class TestValues
    {
        public string test1 { get; set; }
        public string test2 { get; set; }
        public string test3 { get; set; }
    }

public class Conf_Parity : PageModel
    {
    public static JsonResult OnPost(TestValues myString)
        {
             var test = myString;
             return new JsonResult("");
        }
    }
}
var output = {
    test1: 'hallo',
    test2: 'peter',
    test3: 'how are you'
};
console.log(output);

$.ajax({
    type: "POST",
    url: "Conf_Parity",
    dataType: "json",
    data: JSON.stringify(output),
    contentType: "application/json; charset=utf-8",                                
    beforeSend: function (xhr) {
        xhr.setRequestHeader("XSRF-TOKEN",
            $('input:hidden[name="__RequestVerificationToken"]').val());
    },                                                                
    failure: function (response) {
        alert(response);
    }
});

1 个答案:

答案 0 :(得分:0)

我一般不会将JSON发布到页面处理程序。这样做几乎没有充分的理由。在将JSON.stringify方法应用到表单数据之前,我将按照您的要求发布表单数据。我只会将JSON发布到需要它的API端点。

但是如果无论如何要发布JSON,都需要从Request正文访问JSON并反序列化:

public async Task OnPostAsync()
{

    using (var reader = new StreamReader(Request.Body, Encoding.UTF8))
    {
        var body = await reader.ReadToEndAsync();
        var testValues = JsonConvert.DeserializeObject<TestValues>(body);
        // do something with testValues.test1 etc.
    }
}

注意-OnPostAsync处理程序没有参数。模型绑定不适用于JSON。