每个帖子请求的ASP MVC - Html.Action [post]触发

时间:2017-04-30 18:21:48

标签: asp.net asp.net-mvc

我在我创建的网站上有一份简报订阅表(它是布局的一部分),我在layout.cshtml文件中使用Html.Action()来调用我的订阅()动作方法。该方法有两个'版本:一个用于获取,另一个用于发布请求。

问题:

  • 每当提交任何其他表单时,都会调用Subscribe()POST操作方法 - 我不想这样:只有当有人点击“订阅”时才会调用它。按钮(然后有一个ajax调用来更新页面而不重新加载)
  • 例如,在我的联系人页面中,当我提交表单时,也会调用Subscribe()post方法

我不确定为什么会这样,但我相信这是因为有一个帖子请求,因此我的Subscribe()POST方法被自动调用而不是Subscribe()GET one.I尝试使用Html .Partial for this,但它不起作用,因为我必须通过layout.cshtml文件将模型传递给局部视图

_layout.cshtml:

// more code
 @Html.Action("Subscribe", "Newsletter", new { area = "" })
// mode code

NewsletterController:

public ActionResult Subscribe()    {
        NewsletterSubscribeVM model = new NewsletterSubscribeVM();
        return PartialView("NewsletterSubscription", model);
    }

/// always gets called, even when it shouldn't     
        [HttpPost, ValidateAntiForgeryToken]
        public ActionResult Subscribe(NewsletterSubscribeVM subscriber) {
            string message;
            if (!ModelState.IsValid) {
                message = "Ops! Something went wrong.";
                return Json(message, JsonRequestBehavior.AllowGet);
            }
            Newsletter sub = new Newsletter { Email = subscriber.SubscriberEmail };
            this._service.Add(sub);
            message = "Thank you for subscribing!";
            return Json(message, JsonRequestBehavior.AllowGet);
        }
    }

NewsletterSubscription.chtml

@model Web.ViewModels.NewsletterSubscribeVM

@using (Html.BeginForm("Subscribe", "Newsletter", new { area = "" }, FormMethod.Post, new { id = "newsletter-form", @class = "col-xs-12" })) {
    @Html.AntiForgeryToken()

    @Html.Label("Subcribe!", new { id = "newsletter-msg", @class = "col-xs-12 no-padding" })
    @Html.TextBoxFor(m => m.SubscriberEmail, new { placeholder = "Email", @class = "col-xs-7", id = "newsletter-box" })
    <button id="newsletter-btn" class="col-xs-1">
        <i class="fa fa-arrow-right absolute-both-centered" aria-hidden="true"></i>    </button>
}

使用Javascript:

$('#newsletter-btn').click(function (e) {
            var form = $('#newsletter-form');
            e.preventDefault();

            // if the user has inserted at least one character and the 'thank you' msg isn't showing yet:
            if ($('#newsletter-box').val().length != 0 && $('#subscription-status-msg').length == 0) {
                $.ajax({
                    method: "POST",
                    url: "/newsletter/subscribe",
                    data: form.serialize(),
                    dataType: "json",
                    success: function(data) {
                        $('<div id="subscription-status-msg" class="col-xs-12 no-padding">' + data + '</div>').appendTo($("#newsletter-form")).hide().fadeIn(500);
                    }
                })
            }
    })

提前致谢!

0 个答案:

没有答案