【问题标题】:ASP.NET MVC - AJAX Submit Form does not fire appropriate eventASP.NET MVC - AJAX 提交表单不触发适当的事件
【发布时间】:2017-05-11 11:26:45
【问题描述】:

在我的 personDetails.cshmtl 文件中,我有以下表格:

<form id="userUpdateForm" method="post">
    <fieldset>
        <legend>User Details</legend>
        <input type="checkbox" name="authorisedCheckbox" value="Authorised" id="authCheck" />Authorised<br />
        <input type="checkbox" name="enabledCheckbox" value="Enabled" id="eCheck" />Enabled<br />
    </fieldset>
    <fieldset>
        <input type="hidden" name="personId" id="idCheck" value='@ViewData["personId"]'>
    </fieldset>
    <input type="submit" value="Save Changes" name="Save Changes">
    <button type="button">Cancel</button>
</form>

然后我在页面下方有 Javascript,如下所示:

$('#userUpdateForm').submit(function (e) {
        var personDetails = {
            Enabled: $('#eCheck').val(),
            Authorised: $('#authCheck').val(),
            Id: $('#idCheck').val()
        };

        $.ajax({
            type: "POST",
            url: '<%= Url.Action("submitForm", "Home") %>',
            data: JSON(personDetails),
            //contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (result) {
                '@Url.Action("Index", "Home")';
            },
            error: function (result) {
                alert("A problem occured when submitting the form.");
            }
        });

        return false;
    });

当点击提交按钮时,Javascript 会触发。首先,“HomeController”中的“submitForm”方法被触发,然后它也重定向回“HomeController”中的“Index”,它只输出一个视图。

“submitForm”目前类似于以下内容:

       [HttpPost]
        public ActionResult submitForm(JsonResult jsonForm)
        {
            System.Diagnostics.Debug.WriteLine("made it here");
            System.Diagnostics.Debug.WriteLine(jsonForm);
            return View();
        }

所以我的问题是:我在当前表单中缺少什么来触发 AJAX 事件?我相当确定它当前没有触发,因为它应该触发的方法没有警报并且控制台上没有任何输出。

我宁愿不要过多地更改表单本身,因为我目前还有另一位 Javascript 可以将复选框设置为在适当的情况下检查 onload。

编辑:我根据 Stephen Muecke 的建议修复了该方法。我在这里要做的是:点击按钮->将详细信息提交到我的submitForm方法-> submitForm方法获取详细信息并在数据库中执行一些操作->完成后返回成功->成功时,从personDetails.cshtml重定向到index.cshtml。

【问题讨论】:

  • success: function (result) { '@Url.Action("Index", "Home")'; } 没有做任何事情。这是一个错字吗?您是否检查了网络选项卡以查看 ajax 调用是否正在触发,以及响应正文中有什么?那将是最简单的查看方式。另外,为什么您的 ajax 方法接受“JsonResult”对象?那应该是 return 类型。它应该接受与表单字段对应的视图模型对象。
  • 而且您不应该从 ajax 方法返回整个视图 - 这将返回带有所有标签的整个 HTML 页面 - 您不能将其插入到您的页面中。您应该返回一些 Json 数据(使用 JsonResult)或部分视图。
  • 最后,与其在提交方法的末尾执行return false;,不如将​​e.preventDefault(); 作为方法的第一行更安全。这样可以确保在 Javascript 有时间完成之前,它完全没有机会进行正常的回发。
  • 你不能混合使用 aspx (&lt;%= Url.Action("submitForm", "Home") %&gt; 和 razor (@Url.Action("Index", "Home"))。但是你想在这里做什么。你调用一个返回视图但从不做任何事情的方法。跨度>
  • 我将其更改为 url: '@Url.Action("submitForm", "Home")',现在它正在使用我的方法,谢谢。再次编辑问题以反映我正在尝试做的事情。

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


【解决方案1】:

您需要创建另一个类,该类应包含您发布到 submitForm 操作方法的所有属性。

当前您使用的 JsonResult 类不包含您尝试发布的属性,因此 ModelBinder 不会在此处绑定数据。参考Model Binder..很棒的文章...喜欢它....

   public class personDetails {
        public string Enabled {get;set;}
        public string Authorised {get;set;}
        public string Id {get;set;}
    } 
[HttpPost]
        public ActionResult submitForm(personDetails ObjpersonDetails)
        {
            System.Diagnostics.Debug.WriteLine("made it here");
            System.Diagnostics.Debug.WriteLine(jsonForm);
            return View();
        }

【讨论】:

    【解决方案2】:

    例子:

    型号:

    public class MyModel{
            public string Id {get;set;}
            public string Authorised {get;set;}
            public string Enabled {get;set;}
        } 
    

    行动:

    [HttpPost]
            public ActionResult submitForm(MyModel model)
            {
                System.Diagnostics.Debug.WriteLine("made it here");
                System.Diagnostics.Debug.WriteLine(jsonForm);
                return View();
            }
    

    脚本:

    $('#userUpdateForm').submit(function (e) {
            var personDetails = {
                Id: $('#idCheck').val(),
                Authorised: $('#authCheck').val(),
                Enabled: $('#eCheck').val()
            };
    
            $.ajax({
                type: "POST",
                url: '@Url.Action("submitForm", "Home")',
                contentType: "application/json",
                data: JSON.stringify({ model: personDetails })
                success: function (result) {
                    window.location.href = "/home/index/";              
                },
                error: function (result) {
                    alert("A problem occured when submitting the form.");
                }
            });
    
            return false;
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-07
      • 1970-01-01
      • 1970-01-01
      • 2012-02-22
      • 1970-01-01
      相关资源
      最近更新 更多