Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/34.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript asp.net-mvc ajax json向控制器发送操作方法_Javascript_Asp.net_.net_Ajax_Asp.net Mvc - Fatal编程技术网

Javascript asp.net-mvc ajax json向控制器发送操作方法

Javascript asp.net-mvc ajax json向控制器发送操作方法,javascript,asp.net,.net,ajax,asp.net-mvc,Javascript,Asp.net,.net,Ajax,Asp.net Mvc,我知道同样的问题也有答案,但它们在我的项目中不起作用。 我向员工发送了一条信息。 我喜欢ajax。 我从db收到的电子邮件。但是getEmployeeEmail()会返回我的电子邮件(没错) 控制器名称:EmployerActivity 当我发送邮件时,代码不起作用。 我的ajax帖子代码: $(document).ready(function () { $(".buttonSendEmail").click(function () { var order

我知道同样的问题也有答案,但它们在我的项目中不起作用。 我向员工发送了一条信息。 我喜欢ajax。 我从db收到的电子邮件。但是getEmployeeEmail()会返回我的电子邮件(没错) 控制器名称:EmployerActivity

当我发送邮件时,代码不起作用。 我的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();}

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

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

2) 由于您正在向包含
[ValidateAntiForgeryToken]
属性的POST方法发送AJAX请求,因此有必要将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");
}

除此之外,如果您希望在提交后将整个viewmodel内容传递给POST action方法,或者使用重定向和
RedirectToAction()
,那么您应该使用普通表单提交(和
Html.BeginForm()
helper)来代替;charset=utf-8',选项(或者您需要对数据进行字符串化-
data:JSON.stringify({id:1}),
)。您可以删除无意义的
traditional:true,
选项(您不是在发送简单数组)。然后您需要删除
数据类型:“json”,
(您没有返回json)