【问题标题】:asp.net-mvc ajax json post to controller action methodasp.net-mvc ajax json 发布到控制器操作方法
【发布时间】:2019-03-30 09:17:09
【问题描述】:

我知道同样的问题有答案,但它们在我的项目中不起作用。 如果我向员工发送消息,我有控制器。 id 我用 ajax。 我从 db 收到的电子邮件。但是 getEmployeeEmail() 将我的电子邮件返回给我(没错) 控制器名称:EmployersActivity

当我发送帖子时,代码不起作用。 我的ajax邮编:

$(document).ready(function () {
        $(".buttonSendEmail").click(function () {
            var orderText = $(".orderData").text();
            alert(orderText);
            $.ajax({
                type: "POST",
                contentType: 'application/json; charset=utf-8',
                url: "@(Url.Action("Create", "EmployersActivity"))",
                data: { id: 1 },
                dataType: "json",
                traditional: true,
                error: function (message) {
                    alert("error on start")
                    $(".contentReqGood").show();
                    redirect();
                },
                success: function (result) {
                    if (result.status === 1) {
                        alert("error")
                    } else {
                        $(".contentReqGood").show();
                        redirect();}})})});

asp.net mvc 代码:

    [HttpGet]
    [Authorize]
    public ActionResult Create()
    {
        return View();
    }

    [HttpPost]
    [Authorize]
    [ValidateAntiForgeryToken]
    public ActionResult Create(int? id)
    {
        if (id == null)
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);

        var email = db.employees.Find(id);
        if (email == null)
            return HttpNotFound();
        if (email != null)
        {


            if (db.SaveChanges() == 1)
            {
                string mailTemplate;
                string title = "asdasd";
                string preview = "asdasdasd";
                var sr = new StreamReader(Server.MapPath("~/App_Data/Templates/" + "InfoEmail.txt"));

                mailTemplate = sr.ReadToEnd();

                string messageBody = string.Format(mailTemplate, title, preview);

                new MailSender
                {
                    Sender = "news@omegasoftware.eu",
                    Recipient = "news@omegasoftware.eu",
                    RecipientsBcc = getEmployeeEmail(),
                    Subject = title,
                    Body = messageBody
                }.Send();}}
        return View();}

【问题讨论】:

  • 删除 contentType: 'application/json; charset=utf-8', 选项(或者您需要对数据进行字符串化 - data: JSON.stringify({ id: 1 }),)。您可以删除无意义的traditional: true, 选项(您不是发送简单的数组)。然后你需要删除dataType: "json",(你没有返回json)

标签: javascript asp.net .net ajax asp.net-mvc


【解决方案1】:

您对当前示例有几个问题:

1) [Authorize] 属性在 POST 方法中是不必要的,因为在 GET 操作方法中使用它应该足以防止未经授权的用户。

2) 由于您将 AJAX 请求发送到包含 [ValidateAntiForgeryToken] 属性的 POST 方法,因此有必要将 CSRF 预防令牌发送到 AJAX 请求中。

3) 删除 dataType: "json"contentType: 'application/json; charset=utf-8'traditional: true,因为您发送的是单个整数数据,而不是使用数组或 JSON 格式的字符串。

4) AJAX 回调旨在保持在同一页面中,因此应将return View() 替换为return PartialView()

基于以上 4 个问题,如果需要使用 AJAX,您应该像下面的示例一样设置请求和控制器操作:

AJAX 请求

$(document).ready(function () {
    $(".buttonSendEmail").click(function () {
        var orderText = $(".orderData").text();
        alert(orderText);

        var form = $('form');
        var token = $('input[name="__RequestVerificationToken"]', form).val();

        $.ajax({
            type: "POST",
            url: "@Url.Action("Create", "EmployersActivity")",
            data: { id: 1, __RequestVerificationToken: token },
            error: function (message) {
                alert("error on start");
                // other stuff
            },
            success: function (result) {
                $(".contentReqGood").show();
                // other stuff
            }
        });
    });
});

控制器动作

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(int? id)
{
    if (id == null)
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);

    var email = db.employees.Find(id);
    if (email == null)
        return HttpNotFound();
    if (email != null)
    {
        // do something
    }
    return PartialView("_PartialViewName");
}

除此之外,如果您想在提交后将整个视图模型内容传递给 POST 操作方法或使用RedirectToAction() 重定向,那么您应该改用普通表单提交(使用Html.BeginForm() 助手)。

【讨论】:

    猜你喜欢
    • 2011-05-06
    • 1970-01-01
    • 2019-01-26
    • 1970-01-01
    • 2014-04-04
    • 2016-05-28
    • 2017-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多