从jQuery的回调没有得到到控制器/动作 [英] Callback from jQuery not getting to Controller/Action

查看:183
本文介绍了从jQuery的回调没有得到到控制器/动作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个与我们联系在MVC应用程序中使用jQuery的模式对话框形成。该框弹出了罚款,但是当我在对话框中点击提交按钮,它没有得到我的操作方法。我已经尝试了一些东西,但无法弄清楚什么是错的。有人可以看到我可能做错了吗?谢谢你。

PartialView(联系我们的形式):

  @model BackgroundSoundBiz.Models.EmailModel<表ID =sendEmailForm>
    < D​​IV ID =sendForm>
        @ Html.LabelFor(M = GT; m.senderName)LT; BR />
        @ Html.TextBoxFor(M = GT; m.senderName)
        < BR />
        @ Html.LabelFor(M = GT; m.senderEmail)LT; BR />
        @ Html.TextBoxFor(M = GT; m.senderEmail)
        < BR />
        @ Html.LabelFor(M = GT; m.message)LT; BR />
        @ Html.TextAreaFor(M = GT; m.message)
        < BR />
        <输入类=关闭NAME =提交类型=提交值=提交/>
    < / DIV>
< /表及GT;

型号:

 公共类EmailModel
    {
        [需要]
        [显示(名称=名称)]
        公共字符串SENDERNAME {搞定;组; }        [需要]
        [显示(名字=电子邮件)]
        公共字符串SENDEREMAIL {搞定;组; }        [需要]
        [显示(名称=消息)
        公共字符串消息{搞定;组; }
    }

jQuery的:

 <脚本类型=文/ JavaScript的>
        $ .ajaxSetup({缓存:假});        $(文件)。就绪(函数(){
            $(。openDialog)。在(点击,功能(E){
                亦即preventDefault();
                $(< D​​IV>< / DIV>中)。addClass(对话)
                    .attr(ID,$(本).attr(数据对话框-ID))
                    .appendTo(身体)
                    。对话({
                        标题:$(本).attr(数据对话框标题),
                        关闭:函数(){$(本)上卸下摆臂()},
                        宽度:500,
                        高度:350,
                        显示:{大意是:盲人,时间:1000},
                        隐藏:{大意是:爆炸,时间:1000},
                        模式:真
                    })负载(this.href)。
            });            $(亲密)。在(点击,功能(E){
                亦即preventDefault();                。VAR SENDERNAME = $(#NAME)VAL();
                。VAR SENDEREMAIL = $(#电子邮件)VAL();
                VAR消息= $(#消息)文本()。                $阿贾克斯({
                    键入:POST,
                    网址:/首页/ SendEmail
                    数据:{发出者:SENDERNAME,SENDEREMAIL:SENDEREMAIL,消息:消息},
                    成功:功能(数据){
                        警报(您的电子邮件已成功发送。);
                        $(本).closest(对话)对话框(关闭)。
                    },
                    错误:功能(数据){
                        警报(有发送电子邮件的错误,请重试或联系系统管理员。);
                        $(本).closest(对话)对话框(关闭)。
                    }
                })
            });
        });
    < / SCRIPT>

控制器:

 公众的ActionResult SendEmail()
        {
            返回PartialView(SendEmail,新EmailModel());
        }        [HttpPost]
        公众的ActionResult SendEmail(EmailModel模型)
        {
            布尔isSuccessful = TRUE;            如果(ModelState.IsValid)
            {
                //发电子邮件
            }            返回JSON(isSuccessful);
        }


解决方案

您使用动态添加的形式向DOM .load(this.href); 这意味着你需要使用事件代表团来处理按钮。更改

  $(亲密)。在(点击,功能(E){

 的$(document)。在('点击','.close'功能(E){`

虽然你应该更换文件与网页上存在当你第一次渲染视图中最近的祖先。

此外,您的jQuery选择不正确,你将不会被发布与您的模型中的任何值。正确的选择是基于 ID 属性所产生的的HtmlHelper 方法

  VAR SENDERNAME = $(#SENDERNAME)VAL();
VAR SENDEREMAIL = $(#SENDEREMAIL)VAL()。
VAR消息= $(#消息)VAL()。

但它能够更好地使用 .serialize()方法,该方法将正确序列化表单控件

  $。阿贾克斯({
    键入:POST,
    网址:'@ Url.Action(SendEmail,家)',//不要硬code
    数据:$('#sendEmailForm')序列化()。
    成功:功能(数据){
        ....

I have a contact us form in a modal dialog box using jQuery in an MVC application. The box popups up fine, but when I click on the submit button in the dialog box, its not getting to my action method. I've tried a few things, but can't figure out what's wrong. Can someone see what I might be doing wrong? Thanks.

PartialView (Contact Us form):

@model BackgroundSoundBiz.Models.EmailModel

<form id="sendEmailForm">
    <div id="sendForm">
        @Html.LabelFor(m => m.senderName)<br />
        @Html.TextBoxFor(m => m.senderName)
        <br />
        @Html.LabelFor(m => m.senderEmail)<br />
        @Html.TextBoxFor(m => m.senderEmail)
        <br />
        @Html.LabelFor(m => m.message)<br />
        @Html.TextAreaFor(m => m.message)
        <br />
        <input class="close" name="submit" type="submit" value="Submit" />
    </div>
</form>

Model:

    public class EmailModel
    {
        [Required]
        [Display(Name = "Name")]
        public string senderName { get; set; }

        [Required]
        [Display(Name = "Email")]
        public string senderEmail { get; set; }

        [Required]
        [Display(Name = "Message")]
        public string message { get; set; }
    }

jQuery:

<script type="text/javascript">
        $.ajaxSetup({ cache: false });

        $(document).ready(function () {
            $(".openDialog").on("click", function (e) {
                e.preventDefault();
                $("<div></div>").addClass("dialog")
                    .attr("id", $(this).attr("data-dialog-id"))
                    .appendTo("body")
                    .dialog({
                        title: $(this).attr("data-dialog-title"),
                        close: function () { $(this).remove() },
                        width: 500,
                        height: 350,
                        show: { effect: "blind", duration: 1000 },
                        hide: { effect: "explode", duration: 1000 },
                        modal: true
                    }).load(this.href);
            });

            $(".close").on("click", function (e) {
                e.preventDefault();

                var senderName = $("#Name").val();
                var senderEmail = $("#Email").val();
                var message = $("#Message").text();

                $.ajax({
                    type: "POST",
                    url: "/Home/SendEmail",
                    data: { "senderName": senderName, "senderEmail": senderEmail, "message": message },
                    success: function (data) {
                        alert("Your email was successfully sent.");
                        $(this).closest(".dialog").dialog("close");
                    },
                    error: function (data) {
                        alert("There was an error sending your email.  Please try again or contact system administrator.");
                        $(this).closest(".dialog").dialog("close");
                    }
                })
            });
        });
    </script>

Controller:

        public ActionResult SendEmail()
        {
            return PartialView("SendEmail", new EmailModel());
        }

        [HttpPost]
        public ActionResult SendEmail(EmailModel model)
        {
            bool isSuccessful = true;

            if (ModelState.IsValid)
            {
                //send email
            }

            return Json(isSuccessful);
        }

解决方案

You dynamically adding the form to the DOM using .load(this.href); which means you need to use event delegation to handle the button. Change

$(".close").on("click", function (e) {

to

$(document).on('click', '.close', function(e) {`

although you should replace document with the closest ancestor that exists on the page when you first render the view.

In addition, your jQuery selectors are incorrect and you will not be posting any values related to your model. The correct selectors are based on the id attributes generated by the HtmlHelper methods are

var senderName = $("#senderName").val();
var senderEmail = $("#senderEmail").val();
var message = $("#message").val();

however its better to use the .serialize() method which will correctly serialize your form controls

$.ajax({
    type: "POST",
    url: '@Url.Action("SendEmail", "Home")', // don't hard code
    data: $('#sendEmailForm').serialize(),
    success: function (data) {
        ....

这篇关于从jQuery的回调没有得到到控制器/动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆