MVC4 ajax形式不起作用

时间:2013-09-05 15:56:46

标签: c# asp.net-mvc-4

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

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

我的问题有两个。

  1. 数据被插入数据库两次

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

  3. 我可以使用直接的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>
    

    AboutController

     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>
    

    ---- UPDATE

    这是我的BundleConfig.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>
    

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

    我的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);
            }
        }
    

1 个答案:

答案 0 :(得分:1)

你忘了在部分地区放置一个#ajaxreplace div:

<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方法有问题。