Ajax呼叫突然停止,而是转到Http Post

时间:2019-05-23 08:06:23

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

我有一个表单,当用户单击一个按钮并填写表单的某些部分时,将替换整个html模板(我这样做是为了指导用户首先填写的内容)。问题是最后我执行了ajax调用以将所有更改保存到数据库,但是与其转到ajax调用的succes函数,它转到控制器操作的httppost并使应用程序崩溃。

这是带有模板的我的html代码:

<h2>Nieuwe testrit</h2>

<p>
<input type="button" class="btn btn-primary" value="Terug naar lijst" 
 onclick="location.href='@Url.Action("index", "TestDrive")'" />
 </p>

@using (Html.BeginForm())
{
@Html.AntiForgeryToken()

<div class="form-horizontal">
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group" id="stepReloadDiv">
    @Html.Label("Auto", htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        <div class="form-inline">
            <input type="text" class="form-control" id="selectCarVIN" value="Selecteer een auto." readonly="readonly" />
            <input type="button" class="btn btn-primary btn-outline" value="Auto selecteren" onclick="SelectCar()" />
        </div>
        <br />
        <button class="btn btn-success" onclick="numberOfDays()" ; id="buttonNumberOfDays" disabled>Next <i class="fas fa-arrow-right"></i></button>
        @Html.Hidden("carId")
        @Html.ValidationMessageFor(model => model.carId, "", new { @class = "text-danger" })
    </div>
    </div>
</div>
}



@section Scripts {
<script src="~/Scripts/CustomTestDriveAddScript.js"></script>
<script>
    function SelectCar() {
        var w = $(window).width() - 700;
        var h = $(window).height() - 100;
        $('#cboxLoadingGraphic').show();
        $.colorbox({
            href: '@Url.Action("selectcarfortestdrive","car")',
            iframe: true,
            fastIframe: false,
            transition: 'elastic',
            innerWidth: w,
            innerHeight: h,
            scrolling: true
        });
    }

function SelectCustomer() {
    var w = $(window).width() - 100;
    var h = $(window).height() - 100;
    $('#cboxLoadingGraphic').show();
    $.colorbox({
        href: '@Url.Action("SelectCustomerForTestDrive","customer")',
        iframe: true,
        fastIframe: false,
        transition: 'elastic',
        innerWidth: w,
        innerHeight: h,
        scrolling: true
    });
}

</script>

<script id="lengthQuestionTemplate" type="text/template">
    <div class="col-md-10  col-md-offset-2">
        <h4>Gaat deze testrit over meer dan 1 uur/meerdere dagen?</h4>
        <div class="form-inline">
            <button class="btn btn-success btn-outline" onclick='nextStepStartDateMultipleDays();'>Ja <i class="fas fa-check-circle" style="color:green"></i></button>
            <button class="btn btn-danger btn-outline" onclick='nextStepStartDateOneDay();'>Nee <i class="fas fa-times-circle" style="color:#af1515"></i></button>
        </div>
    </div>
</script>

<script id="endDateTemplate" type="text/template">
    <div class="col-md-10">
        <div class="form-group">
            @Html.Label("Einddatum", htmlAttributes: new { @class = "control-label col-md-2" })
            @Html.TextBoxFor(model => model.endDate, "{0:yyyy-MM-dd}", new { @class = "form-control", @id = "endDate", @type = "date", @onchange = "endDateChanged();" })
            @Html.ValidationMessageFor(model => model.endDate, "", new { @class = "text-danger" })
        </div>
        <div class="form-group">
            @Html.Label("Eindtijd", htmlAttributes: new { @class = "control-label col-md-2" })
            @Html.DropDownListFor(model => model.endBlockId, new SelectList("", "id", "endTime"), new { @class = "form-control", @id = "endTimeDropdown", @onchange = "endTimeChanged();" })
            @Html.ValidationMessageFor(model => model.endBlockId, "", new { @class = "text-danger" })
        </div>
        <div class="form-group">
            <span id="errorMsg"></span>
            <button class="btn btn-success col-md-offset-2" onclick="nextStepChooseEndDate('endDate', 'endTimeDropdown')" ; id="buttonChooseEndDate" disabled>Next <i class="fas fa-arrow-right"></i></button> 
        </div>      
    </div>
</script>

<script id="startDateTemplate" type="text/template">
    @Html.Label("Startdatum", htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        <div class="form-inline">
            @Html.TextBoxFor(model => model.startDate, new { @class = "form-control", @onchange = "startDateChangedSingle();", @type = "date" })
            @Html.ValidationMessageFor(model => model.startDate, "", new { @class = "text-danger" })
        </div>
        <br />
        <span id="errorMsg"></span>
        <button class="btn btn-success" onclick="nextStepChooseStartDate('startDate');" ; id="buttonTimeSingle" disabled>Next <i class="fas fa-arrow-right"></i></button>
    </div>
</script>

<script id="startDateTemplateMultipe" type="text/template">
    <div class="col-md-10">
        <div class="form-group">
            @Html.Label("Startdatum", htmlAttributes: new { @class = "control-label col-md-2" })
            @Html.TextBoxFor(model => model.startDate, "{0:yyyy-MM-dd}", new { @class = "form-control", @type = "date", @id = "startDate", @onchange = "startDateChangedMultiple();" })
            @Html.ValidationMessageFor(model => model.startDate, "", new { @class = "text-danger" })
        </div>
        <div class="form-group">
            @Html.Label("Starttijd", htmlAttributes: new { @class = "control-label col-md-2" })
            @Html.DropDownListFor(model => model.startBlockId, new SelectList("", "id", "startTime"), new { @class = "form-control", @id = "startTimeDropdown" })
            @Html.ValidationMessageFor(model => model.startBlockId, "", new { @class = "text-danger" })
        </div>
        <div class="form-group">
            <span id="errorMsg"></span>
            <button class="btn btn-success col-md-offset-2" onclick="nextStepChooseStartDateMultiple('startDate', 'startTimeDropdown');" ; id="buttonStartMultiple" disabled>Next <i class="fas fa-arrow-right"></i></button>
        </div>
    </div>

<script id="choseTimeSingle" type="text/template">
    @Html.Label("Starttijd", htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        <div class="form-inline">
            @Html.DropDownListFor(model => model.startBlockId, new SelectList("", "id", "time"), new { @class = "form-control", @id = "timeDropdown", @onchange = "startTimeChangedSingle();" })
            @Html.ValidationMessageFor(model => model.startBlockId, "", new { @class = "text-danger" })
        </div>
        <br />
        <span id="errorMsg"></span>
        <button class="btn btn-success" onclick="nextStepChooseTime('timeDropdown');" ; id="buttonTimeSingle">Next <i class="fas fa-arrow-right"></i></button>
    </div>
</script>

<script id="choseLicenceplate" type="text/template">
    @Html.Label("Nummerplaat", htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        <div class="form-inline">
            @Html.DropDownListFor(model => model.licenceplateId, new SelectList("", "id", "licenceplate1"), new { @class = "form-control", @id = "licensePlateDropdown" })
            @Html.ValidationMessageFor(model => model.licenceplateId, "", new { @class = "text-danger" })
        </div>
        <br />
        <button class="btn btn-success" onclick="nextStepChooseLicenceplate('licensePlateDropdown');" ; id="buttonTimeSingle">Next <i class="fas fa-arrow-right"></i></button>
    </div>
</script>

<script id="choseCustomer" type="text/template">
    @Html.Label("Klant", htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        <div class="form-inline">
            <input type="text" class="form-control" id="selectCustomerId" value="Selecteer een klant." readonly="readonly" />
            @Html.Hidden("customerId")
            <input type="button" class="btn btn-primary btn-outline" value="Klant selecteren" onclick="SelectCustomer()" />
        </div>
        <br />
        <button class="btn btn-success" id="buttonSelectCustomer" onclick="nextStepChooseCustomer('customerId');" disabled>Next <i class="fas fa-arrow-right"></i></button>
    </div>
</script>

<script id="choseType" type="text/template">
    @Html.Label("Type uitlening", htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        <div class="form-inline">
            @Html.DropDownListFor(model => model.customerId, new SelectList(ViewBag.testdriveTypes, "id", "name"), new { @class = "form-control", @id = "testDriveTypeDropDown" })
            @Html.ValidationMessageFor(model => model.testDriveTypeId, "", 
 new { @class = "text-danger" })
        </div>
        <br/>
        <button class="btn btn-success" 
onclick="nextStepFinishEdit('testDriveTypeDropDown');">Aanmaken</button>
    </div>  
</script>

<script id="Done" type="text/template">
    <div class="col-md-10  col-md-offset-2">
            <h4>Uw testrit is succesvol toegevoegd.</h4>
        <br />
        <input type="submit" value="Naar testrit" class="btn btn-default" />
    </div>
</script>
 }

我的ajac电话为:

function nextStepFinishEdit(valueId) {
var value = document.getElementById(valueId).value;
testDriveTypeId = value;
$.ajax({
    type: "GET",
    url: "/NewTestDrives/fundallocation",
    data: {
        "licenseplateId": licencePlateId,
        "carId": carId,
        "startDate": startDate,
        "endDate": endDate,
        "customerId": customerId,
        "testDriveTypeId": testDriveTypeId,
        "startBlockId": startBlockId,
        "endBlockId": endBlockId
    },
    async: false,
    success: function (data) {
        var inner = document.getElementById('stepReloadDiv');
        inner.innerHTML = document.getElementById('Done').innerHTML;
    }
});
}

呼叫将转到的代码:

public async Task FundAllocation(int licenseplateId, int carId, string startDate, string endDate, int customerId, int testDriveTypeId, int startBlockId, int endBlockId)
    {
        NewTestDriveModel testDriveModel = new NewTestDriveModel
        {
            carId = carId,
            customerId = customerId,
            endBlockId = endBlockId,
            endDate = endDate,
            licenseplateId = licenseplateId,
            startBlockId = startBlockId,
            startDate = startDate,
            testDriveTypeId = testDriveTypeId
        };

        var testDrives = testDriveService.GetTestDrivesByDay(Convert.ToDateTime(testDriveModel.startDate));
        var customer = customerService.GetCustomerById(testDriveModel.customerId);
        var usedLicensplates = new List<int>();

        foreach (var drive in testDrives)
        {
            if (drive.startBlockId == testDriveModel.startBlockId)
            {
                usedLicensplates.Add(drive.licenceplateId);
            }

            if (drive.carId == testDriveModel.carId && drive.startBlockId == testDriveModel.startBlockId)
            {
                return;
            }
        }

            TestDrive testDrive = new TestDrive
            {
                carId = testDriveModel.carId,
                customerId = testDriveModel.customerId,
                endBlockId = testDriveModel.endBlockId,
                endDate = Convert.ToDateTime(testDriveModel.endDate),
                licenceplateId = testDriveModel.licenseplateId,
                startBlockId = testDriveModel.startBlockId,
                startDate = Convert.ToDateTime(testDriveModel.startDate),
                testDriveTypeId = testDriveModel.testDriveTypeId
            };

            testDriveId = testDriveService.AddTestDrive(testDrive);
            Session["testDriveId"] = testDriveId;

        CalendarHelper calendarHelper = new CalendarHelper();

        CarService carService = new CarService();
        string licenceplate = licenseplateService.GetLicenceplateById(testDriveModel.licenseplateId).licenceplate1;

        Car car = carService.GetCarById(testDriveModel.carId);

        CarModel newCarModel = new CarModel
        {
            Series = car.series,
            Name = car.name,
            VINNumber = car.VINNumber,
        };

        CalendarEventModel model = new CalendarEventModel()
        {
            CustomerFirstname = customer.firstname,
            CustomerLastname = customer.name,
            TestDrive = testDriveModel,
            Car = newCarModel,
            Licenceplate = licenceplate,
            TestDriveId = testDriveId
        };

        MailHelper mailHelper = new MailHelper();

        TimeBlock startBlock = timeBlockService.GetTimeBlockById(testDriveModel.startBlockId);
        TimeBlock endBlock = timeBlockService.GetTimeBlockById(testDriveModel.endBlockId);

        CustomerReservationConfirmationMailModel mailModel = new CustomerReservationConfirmationMailModel()
        {
            CarSerie = car.series,
            CarName = car.name,
            Motor = car.motor,
            Model = car.modelType,
            StartDate = Convert.ToDateTime(testDriveModel.startDate).ToString("dd/MM/yyyy"),
            EndDate = Convert.ToDateTime(testDriveModel.endDate).ToString("dd/MM/yyyy"),
            StartHour = startBlock.startTime,
            EndHour = endBlock.endTime,
            Customer = customer,
            Licenceplate = licenceplate
        };

        await mailHelper.SendCustomerReservationConfirmationMail(mailModel);

        await calendarHelper.AddEventAsync(model);
    }

我的控制器动作:

        public ActionResult Add()
    {
        ViewBag.Customer = customerService.All();
        ViewBag.testdriveTypes = testDriveTypeService.GetAll();
        return View();
    }

    [HttpPost]
    public ActionResult Add(string s)
    {
        var testDriveId = Session["testDriveId"];
        return RedirectToAction("details", new { id = testDriveId });
    }

因此会触发ajax调用,并且数据库正在更新,但是从未调用过我替换html的成功函数,而是直接转到了我的Http帖子,我该如何防止这种情况。

1 个答案:

答案 0 :(得分:0)

默认情况下,调用nextStepFinishEdit函数的按钮的类型为“提交”。由于您在@ html.BeginForm()中具有此名称,因此它将提交该表格。这就是导致您的POST请求被触发的原因。只需添加type ='button'即可:

     <button class="btn btn-success" type='button'
onclick="nextStepFinishEdit('testDriveTypeDropDown');">Aanmaken</button>