Ajax-вызов внезапно останавливается и вместо этого переходит на Http Post - PullRequest
0 голосов
/ 23 мая 2019

У меня есть форма, где через шаблоны заменяется HTML, когда пользователь нажимает кнопку и заполняет части формы (я делаю это таким образом, чтобы помочь пользователю в том, что он заполняет первым). проблема в конце, я делаю ajax-вызов, чтобы сохранить все изменения в базе данных, но вместо перехода к функции succes-вызова ajax, он переходит в 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 срабатывает, и база данных обновляется, но функция succes, где я заменяю html, никогда не вызывается, вместо этого она напрямую переходит к моему сообщению Http, как я могу предотвратить это.

1 Ответ

0 голосов
/ 23 мая 2019

По умолчанию ваша кнопка, которая вызывает функцию nextStepFinishEdit, будет иметь тип 'submit'.Поскольку у вас есть это внутри вашего @ html.BeginForm (), он отправит эту форму.Это то, что вызывает ваш запрос POST для запуска.Просто добавьте type = 'button' как:

     <button class="btn btn-success" type='button'
onclick="nextStepFinishEdit('testDriveTypeDropDown');">Aanmaken</button>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...