首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >asp.net-mvc ajax json发布到控制器操作方法

asp.net-mvc ajax json发布到控制器操作方法
EN

Stack Overflow用户
提问于 2018-10-25 09:10:20
回答 1查看 677关注 0票数 0

我知道同样的问题也有答案,但在我的项目中不起作用。我有控制器,如果我给员工发信息的话。我用ajax的身份证。我从分局收到的电子邮件。但是getEmployeeEmail()返回我的电子邮件(对)控制器名称: EmployersActivity

当我发邮件时,代码不起作用。我的ajax邮政编码:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
$(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代码:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
    [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();}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-10-25 18:09:53

有关当前示例,您有几个问题:

1)在POST方法中使用[Authorize]属性是不必要的,因为在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请求

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
$(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
            }
        });
    });
});

控制器动作

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
[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");
}

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52994710

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文