MVC4 ajax 表单不起作用

本文关键字:不起作用 表单 ajax MVC4 | 更新日期: 2023-09-27 18:30:14

嗨,我是MVC的新手,所以请耐心等待。

我正在尝试做一个简单的 ajax 表单,它只接受插入并让用户知道记录已保存到数据库中。

我的问题是双重的。

  1. 数据入数据库两次

  2. 编辑器不会被清除,也不会显示消息。

我可以使用直接的 HTML 表单帖子来解决这个问题,但想使用 ajax,然后引入某种加载 gif 或使用 spin.js。

我的代码:

_Layout.cshtml

 <!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
    @Styles.Render("~/Content/css")
    @Styles.Render("~/Content/kendo")
    @Scripts.Render("~/bundles/modernizr")
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/kendo")
    @Scripts.Render("~/bundles/jqueryval")
</head>
<body>
    <div id="wrapper" style="width:100%; text-align:center">
        <img src="~/Content/Header.PNG" alt="MyHeader" />
   </div>
    @RenderBody()

    @RenderSection("scripts", required: false)
</body>
</html>

关于控制器

 public class AboutController : Controller 
    {
        private readonly IMailRepository repository;
        public AboutController(IMailRepository repo)
        {
            repository = repo;
        }
        public ActionResult AboutUs()
        {
            return View();
        }
        public ActionResult CreateMailing()
        {
            return View(new MailRequest());
        }
        [HttpPost]
        public PartialViewResult CreateMailing(MailRequest model)
        {
            if (model == null)
            {
                return PartialView("_MailingData",new MailRequest());
            }
            if (ModelState.IsValid)
            {
                repository.SaveMailRequest(model);
                ModelState.Clear();
                TempData["message"] = string.Format("{0} has been added to the mailing list.", model.Email);
                return PartialView("_MailingData",new MailRequest());
            }
            else
            {
                return PartialView("_MailingData",model);
            }
        }
    }

_MailingDate.cshtml

 @model MyProj.Models.MailRequest
@Html.EditorForModel()
            <br/>
            <input type="submit" value="Save"/>
            <input type="button" value="Cancel"
                   onclick="location.href='@Url.Action("AboutUs", "About")' " />
            @if (TempData["message"] != null)
             {
                 <div>@TempData["message"]</div>
             }

CreateMailing.cshtml

 @model MyProj.Models.MailRequest
@{
    ViewBag.Title = "Mailing List";
    AjaxOptions ajaxOpts = new AjaxOptions
    {
        InsertionMode = InsertionMode.Replace,
        UpdateTargetId = "ajaxreplace"
    };
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Mailing List Request</title>
</head>
<body>
    <div id="ajaxrequest">
        @using (Ajax.BeginForm(ajaxOpts))
        {
            @Html.Partial("_MailingData")
        }
    </div>
</body>
</html>

----更新

这是我的捆绑配置.cs

 public static class BundleConfig
    {
        // For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725
        public static void RegisterBundles(BundleCollection bundles)
        {
            if (bundles == null) return;
            // The jQuery bundle
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                "~/Scripts/jquery-{version}.js"));
            //bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
            //    "~/Scripts/jquery-{version}.js",
            //    "~/Scripts/jquery-migrate-1.1.1.js"));

            bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
                        "~/Scripts/jquery-ui-{version}.js"));
            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.unobtrusive*",
                        "~/Scripts/jquery.validate*"));

            // The Kendo JavaScript bundle
            bundles.Add(new ScriptBundle("~/bundles/kendo").Include(
                "~/Scripts/kendo.all.min.js",
                // or kendo.all.min.js if you want to use Kendo UI Web and Kendo UI DataViz
                "~/Scripts/kendo.aspnetmvc.min.js"));

            bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css"));
            bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(
                        "~/Content/themes/base/jquery.ui.core.css",
                        "~/Content/themes/base/jquery.ui.resizable.css",
                        "~/Content/themes/base/jquery.ui.selectable.css",
                        "~/Content/themes/base/jquery.ui.accordion.css",
                        "~/Content/themes/base/jquery.ui.autocomplete.css",
                        "~/Content/themes/base/jquery.ui.button.css",
                        "~/Content/themes/base/jquery.ui.dialog.css",
                        "~/Content/themes/base/jquery.ui.slider.css",
                        "~/Content/themes/base/jquery.ui.tabs.css",
                        "~/Content/themes/base/jquery.ui.datepicker.css",
                        "~/Content/themes/base/jquery.ui.progressbar.css",
                        "~/Content/themes/base/jquery.ui.theme.css"));
            // The Kendo CSS bundle
            bundles.Add(new StyleBundle("~/Content/kendo").Include(
                "~/Content/kendo.common.*",
                "~/Content/kendo.uniform.*"));

            // Clear all items from the ignore list to allow minified CSS and JavaScript files in debug mode
            bundles.IgnoreList.Clear();

            // Add back the default ignore list rules sans the ones which affect minified files and debug mode
            bundles.IgnoreList.Ignore("*.intellisense.js");
            bundles.IgnoreList.Ignore("*-vsdoc.js");
            bundles.IgnoreList.Ignore("*.debug.js", OptimizationMode.WhenEnabled);
        }

    }

我认为我的数据库问题可能与我最终在页面的 html 中出现以下内容的事实有关

    <script src="/bundles/modernizr"></script>
    <script src="/Scripts/jquery-2.0.0.js"></script>
<script src="/Scripts/jquery-2.0.3.js"></script>
    <script src="/Scripts/kendo.all.min.js"></script>
<script src="/Scripts/kendo.aspnetmvc.min.js"></script>
    <script src="/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script src="/Scripts/jquery.validate.js"></script>
<script src="/Scripts/jquery.validate.min.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.min.js"></script>

我猜我不应该同时注册完整和最小 js 脚本,但不确定在仍然使用捆绑包的同时防止这种情况的最佳方法

My EFMailRepository

public class EFMailRepository : IMailRepository, IDisposable
    {
        private EFDbContext context = new EFDbContext();

        public void SaveMailRequest(MailRequest mailRequest)
        {
            context.MailingList.Add(mailRequest);
            context.SaveChanges();
        }
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                // dispose managed resources
                context.Dispose();
            }
            // free native resources
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }

MVC4 ajax 表单不起作用

你忘了在部分周围放一个#ajaxreplacediv:

<div id="ajaxrequest">
    @using (Ajax.BeginForm(ajaxOpts))
    {
        <div id="ajaxreplace">
            @Html.Partial("_MailingData")
        </div>
    }
</div>

您在 AjaxOptions 中使用此 id,因此您应该在 DOM 中有一个相应的元素,该元素将根据 AJAX 请求的结果进行更新:

AjaxOptions ajaxOpts = new AjaxOptions
{
    InsertionMode = InsertionMode.Replace,
    UpdateTargetId = "ajaxreplace"
};

就您关于将数据插入两次到数据库中的第一个问题而言,您尚未提供有关 DAL 层的足够详细信息,以便我们能够进一步诊断该问题。也许您的repository.SaveMailRequest方法有问题。