无法从控制器向ajax发送JSON数据

时间:2019-05-21 23:53:46

标签: c# json ajax model-view-controller

我有一个ajax / json / c#问题。我认为我正在做我在其他帖子中阅读的所有内容,但仍无法正常工作。很有可能是飞行员错误,但我很想念它。

任何想法表示赞赏。

数据从电子邮件表单中获取,并发送到控制器以发送电子邮件。电子邮件被发送!可行。

我尝试将数据返回给ajax,但这似乎不起作用。

    [HttpPost]
    public JsonResult Sendemail(EmailStuff emailstuff)
    {
        string msg = sendmail(emailstuff); //this works fine - msg is returned as "ok"
        if (msg=="ok")
        {
            SendAutoReply();// this gets done
            return Json(new { success = true, message = msg }, JsonRequestBehavior.AllowGet);
        }
        return Json(new { success = false, message = msg }, JsonRequestBehavior.AllowGet); 
    }
//jquery
    $('#emailbtn').on('click', function (event) {
    //...get form data...
        var myData = {
            UserName: name, UserEmail: email, UserPhone: phone, UserAddress: address,
            UserSubject: subject, UserMessage: msg, UserList: emList
        };
    $.ajax({
            type: "POST",
            contentType: "application/json;charset=utf-8",
            processData: false,
            dataType: "json",
            url: $('#baseurl').text() + "email/sendemail",

            data: JSON.stringify(myData),
            success: function (response) {
                if (response.success === true) {
                    window.location = "email-ok";
                } else {
                    window.location = "email-error?msg="+response.message;
                }
            },
            error: function (response) {
                window.location = "email-error?msg=uhoh";
    })
})

在控制器中,字符串msg设置为“ ok”。

我期望ajax success:函数将被触发,然后if语句将评估response.success并重定向到email-ok或email-error页面。

但是发生的是错误:调用函数,并将重定向重定向到带有错误消息“ uhoh”的电子邮件错误页面

我唯一知道的测试是Chrome DevTools>网络> XHR>预览 并显示:无法加载响应数据

因此,似乎响应对象未正确发送。

预先感谢

编辑 响应标题显示500错误-不确定是什么原因

    Response Header from Dev Tools
    cache-control: private
    cf-ray: 4daaae4d1eca9f46-IAD
    content-type: text/html; charset=utf-8
    date: Wed, 22 May 2019 00:30:20 GMT
    expect-ct: max-age=604800, report-uri="https://report- 
    uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
    server: cloudflare
    status: 500
    x-aspnet-version: 4.0.30319
    x-aspnetmvc-version: 5.2
    x-powered-by: ASP.NET

编辑2

第二行显示错误,错误消息为“无法加载资源,服务器响应状态为500”

    //line 3954 of jquery-3.2.1.min.js.formatted 
    try {
            h.send(b.hasContent && b.data || null)
        } catch (i) {
          if (c)
             throw i
       }

1 个答案:

答案 0 :(得分:0)

似乎我有2个(愚蠢的)问题重叠了。除了控制器代码中显示的SendAutoReply之外,还有一个保存操作,这里没有显示。我已经删除了两者进行测试,但同时智能建议我将return语句更改为元组

正确的

    return Json(new { success = false, message = msg }, JsonRequestBehavior.AllowGet); 

到 错误

    return Json(( success = false, message = msg ), JsonRequestBehavior.AllowGet); 
~~~

So there were 2 problems. I corrected the Json statement but it took me a while to  
remove the Save statement - once I did that it worked.  Still not sure why there was a 500 error
Thanks for the suggestions