每次发送表单时都会触发ajax post double触发器

时间:2016-10-14 18:27:11

标签: ajax forms asp.net-mvc-5

我使用asp.net mvc5并尝试将表单发布到控制器而不使用ajax刷新页面。但问题是,每次按下提交按钮,它都会多次发送数据。只有第一次提交表格一次。但第二次发送两次,第三次发送四次......

这是我的控制器

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using UniProject.Models;

namespace UniProject.Controllers
{
  public class TestController : Controller
    {
    MyContext db = new MyContext();
    // GET: Test
    [HttpGet]
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Create(Test test)
    {
        try
        {
            if (ModelState.IsValid)
            {
                db.Tests.Add(test);
                db.SaveChanges();
                ViewBag.Record = "Data Inserted";
                return PartialView("Index");
            }
            else
            {
                ViewBag.Record = "Error";
                return View(test);
            }
        }
        catch
        {
            ViewBag.Record = "Error";
            return View();
        }
    }
  }
}

这是我的观点

@model UniProject.Models.Test

@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}

<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>

<h2>Index</h2>

<div id="div">
    @Html.Partial("Form" , Model)
</div>

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

我的PartialView

@model UniProject.Models.Test

@using (Ajax.BeginForm("Create" , "Test" , new AjaxOptions { HttpMethod =    "post" , UpdateTargetId = "div"}))
{
    @Html.AntiForgeryToken()

<div class="form-horizontal">
    <h4>Test</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.TestName, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.TestName, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.TestName, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.TestTitle, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.TestTitle, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.TestTitle, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
</div>
}

单击提交按钮后的表单视图 Form Image

这是数据库图像 Database Records

请帮我解决这个问题。提前谢谢......

0 个答案:

没有答案