Я пытаюсь получить результат от функции под названием «validateScheduleDate()», и только если результат поступает от функции, должна быть выполнена следующая строка кода. Я пытаюсь проверить две даты и найти, что эти даты находятся в заданном интервале времени.
Сейчас он не ожидает результата от функции под названием «validateScheduleDate»
Вот мой код на Jvascript
$wizard.wizard({
validateTab: function (currentTab) {
validateScheduleDate().then(function (data) {
if (data != 'noDifference') {
// Not passed to the next line
}
});
switch (currentTab.index()) {
case 0: // tabPaneNames.general
return validateSales1()
case 1: // tabPaneNames.problems
return validateSales2()
case 2: // tabPaneNames.serviceProviders
return validateSales3()
default:
return false;
}
}
});
$('[submit-sales').click(function (event) {
event.preventDefault();
validateScheduleDate().then(function (data) {
if (data == 'noDifference') {
validateTabs(function () { submitForm(); }, true);
}
else{
// Not passed to the next line
}
});
});
function validateScheduleDate() {
var startDate = document.getElementById('dispatch-start-date').value;
var startTime = document.getElementById('ddl-dispatch-times').value;
var arrivalTimeFrame = parseFloat(document.getElementById("hdn-WOArrivalTimeFrame-id").value).toFixed(2);
var scheduledDate = document.getElementById("ScheduledDate").value;
var scheduledTime = document.getElementById("ddl-dispatch-scheduled-times").value;
var dateErrorSpan = document.getElementById("ScheduledDate-Error");
var timeErrorSpan = document.getElementById("ScheduledTime-Error");;
var resultdata = $.get('/WorkOrderDispatch/GetScheduledEndDate', {
dispStartDate: startDate, dispStartTime: startTime, dispTimeFrame: arrivalTimeFrame,
dispScheduledDate: scheduledDate, dispScheduledTime: scheduledTime
}).done(function (result) {
if (result == 'hasDaysDifference') {
timeErrorSpan.textContent = '';
dateErrorSpan.textContent = 'Enter the Scheduled Date within the arrival time frame ' + arrivalTimeFrame + ' Hrs'
$wizard.wizard('changeTo', '#' + tabPaneNames.general);
return false;
}
else if (result == 'hasTimeDifference')
{
dateErrorSpan.textContent = '';
timeErrorSpan.textContent = 'Enter the Scheduled Date within the arrival time frame ' + arrivalTimeFrame + ' Hrs'
$wizard.wizard('changeTo', '#' + tabPaneNames.general);
return false;
}
else {
dateErrorSpan.textContent = '';
timeErrorSpan.textContent = '';
return true;
}
});
return resultdata;
}
Код в контроллере MVC
public async Task GetScheduledEndDate(string dispStartDate, string dispStartTime, string dispTimeFrame, string dispScheduledDate, string dispScheduledTime) {
var UserID = User.Identity.GetUserId();
var loginUser = await DbContext.Employees.Where(x => x.ApplicationUserID == UserID).FirstOrDefaultAsync();
if (loginUser == null)
{
throw new OfficetraxException(ErrorCode.NotFound);
}
TimeZoneInfo employeeTimeZone = TimeZoneTools.FindTimeZone(loginUser.TimeZone);
DateTime now = DateTime.UtcNow;
string DispatchNowString = "[Dispatch Now]";
DateTime startDate = Convert.ToDateTime(dispStartDate);
DateTime scheduledDate;
DateTime? dispatchScheduledDate = null;
if (!string.IsNullOrEmpty(dispScheduledDate))
{
scheduledDate = Convert.ToDateTime(dispScheduledDate);
dispatchScheduledDate = scheduledDate.ApplyTimeAndTimeZone(dispScheduledTime, employeeTimeZone);
}
double? arrivalTimeFrame = Convert.ToDouble(dispTimeFrame);
string combinedscheduleDate = dispScheduledDate + " " + dispScheduledTime;
DateTime dispatchStartDate = dispStartTime == DispatchNowString ? now : startDate.ApplyTimeAndTimeZone(dispStartTime, employeeTimeZone);
DateTime? scheduledEndDate = arrivalTimeFrame.HasValue ?
dispatchStartDate.AddHours(arrivalTimeFrame.Value) : (DateTime?)null;
//DateTime? dispatchScheduledDate = DateTime.Parse(combinedscheduleDate);
if (scheduledEndDate.HasValue && dispatchScheduledDate.HasValue)
{
if(dispatchScheduledDate < dispatchStartDate)
{
if (dispatchScheduledDate.Value.Date == dispatchStartDate.Date)
{
return Json("hasTimeDifference", JsonRequestBehavior.AllowGet);
}
else
{
return Json("hasDaysDifference", JsonRequestBehavior.AllowGet);
}
}
if(dispatchScheduledDate > scheduledEndDate)
{
if(dispatchScheduledDate.Value.Date == scheduledEndDate.Value.Date)
{
return Json("hasTimeDifference", JsonRequestBehavior.AllowGet);
}
else
{
return Json("hasDaysDifference", JsonRequestBehavior.AllowGet);
}
}
else
{
return Json("noDifference", JsonRequestBehavior.AllowGet);
}
}
return Json("noDifference", JsonRequestBehavior.AllowGet);
}
Подробнее здесь: https://stackoverflow.com/questions/788 ... roller-met
Как я могу выполнить асинхронный вызов ajax из Javascript в метод контроллера mvc и дождаться перехода результата к след ⇐ C#
Место общения программистов C#
1722884434
Anonymous
Я пытаюсь получить результат от функции под названием «validateScheduleDate()», и только если результат поступает от функции, должна быть выполнена следующая строка кода. Я пытаюсь проверить две даты и найти, что эти даты находятся в заданном интервале времени.
Сейчас он не ожидает результата от функции под названием «validateScheduleDate»
Вот мой код на Jvascript
$wizard.wizard({
validateTab: function (currentTab) {
validateScheduleDate().then(function (data) {
if (data != 'noDifference') {
// Not passed to the next line
}
});
switch (currentTab.index()) {
case 0: // tabPaneNames.general
return validateSales1()
case 1: // tabPaneNames.problems
return validateSales2()
case 2: // tabPaneNames.serviceProviders
return validateSales3()
default:
return false;
}
}
});
$('[submit-sales').click(function (event) {
event.preventDefault();
validateScheduleDate().then(function (data) {
if (data == 'noDifference') {
validateTabs(function () { submitForm(); }, true);
}
else{
// Not passed to the next line
}
});
});
function validateScheduleDate() {
var startDate = document.getElementById('dispatch-start-date').value;
var startTime = document.getElementById('ddl-dispatch-times').value;
var arrivalTimeFrame = parseFloat(document.getElementById("hdn-WOArrivalTimeFrame-id").value).toFixed(2);
var scheduledDate = document.getElementById("ScheduledDate").value;
var scheduledTime = document.getElementById("ddl-dispatch-scheduled-times").value;
var dateErrorSpan = document.getElementById("ScheduledDate-Error");
var timeErrorSpan = document.getElementById("ScheduledTime-Error");;
var resultdata = $.get('/WorkOrderDispatch/GetScheduledEndDate', {
dispStartDate: startDate, dispStartTime: startTime, dispTimeFrame: arrivalTimeFrame,
dispScheduledDate: scheduledDate, dispScheduledTime: scheduledTime
}).done(function (result) {
if (result == 'hasDaysDifference') {
timeErrorSpan.textContent = '';
dateErrorSpan.textContent = 'Enter the Scheduled Date within the arrival time frame ' + arrivalTimeFrame + ' Hrs'
$wizard.wizard('changeTo', '#' + tabPaneNames.general);
return false;
}
else if (result == 'hasTimeDifference')
{
dateErrorSpan.textContent = '';
timeErrorSpan.textContent = 'Enter the Scheduled Date within the arrival time frame ' + arrivalTimeFrame + ' Hrs'
$wizard.wizard('changeTo', '#' + tabPaneNames.general);
return false;
}
else {
dateErrorSpan.textContent = '';
timeErrorSpan.textContent = '';
return true;
}
});
return resultdata;
}
Код в контроллере MVC
public async Task GetScheduledEndDate(string dispStartDate, string dispStartTime, string dispTimeFrame, string dispScheduledDate, string dispScheduledTime) {
var UserID = User.Identity.GetUserId();
var loginUser = await DbContext.Employees.Where(x => x.ApplicationUserID == UserID).FirstOrDefaultAsync();
if (loginUser == null)
{
throw new OfficetraxException(ErrorCode.NotFound);
}
TimeZoneInfo employeeTimeZone = TimeZoneTools.FindTimeZone(loginUser.TimeZone);
DateTime now = DateTime.UtcNow;
string DispatchNowString = "[Dispatch Now]";
DateTime startDate = Convert.ToDateTime(dispStartDate);
DateTime scheduledDate;
DateTime? dispatchScheduledDate = null;
if (!string.IsNullOrEmpty(dispScheduledDate))
{
scheduledDate = Convert.ToDateTime(dispScheduledDate);
dispatchScheduledDate = scheduledDate.ApplyTimeAndTimeZone(dispScheduledTime, employeeTimeZone);
}
double? arrivalTimeFrame = Convert.ToDouble(dispTimeFrame);
string combinedscheduleDate = dispScheduledDate + " " + dispScheduledTime;
DateTime dispatchStartDate = dispStartTime == DispatchNowString ? now : startDate.ApplyTimeAndTimeZone(dispStartTime, employeeTimeZone);
DateTime? scheduledEndDate = arrivalTimeFrame.HasValue ?
dispatchStartDate.AddHours(arrivalTimeFrame.Value) : (DateTime?)null;
//DateTime? dispatchScheduledDate = DateTime.Parse(combinedscheduleDate);
if (scheduledEndDate.HasValue && dispatchScheduledDate.HasValue)
{
if(dispatchScheduledDate < dispatchStartDate)
{
if (dispatchScheduledDate.Value.Date == dispatchStartDate.Date)
{
return Json("hasTimeDifference", JsonRequestBehavior.AllowGet);
}
else
{
return Json("hasDaysDifference", JsonRequestBehavior.AllowGet);
}
}
if(dispatchScheduledDate > scheduledEndDate)
{
if(dispatchScheduledDate.Value.Date == scheduledEndDate.Value.Date)
{
return Json("hasTimeDifference", JsonRequestBehavior.AllowGet);
}
else
{
return Json("hasDaysDifference", JsonRequestBehavior.AllowGet);
}
}
else
{
return Json("noDifference", JsonRequestBehavior.AllowGet);
}
}
return Json("noDifference", JsonRequestBehavior.AllowGet);
}
Подробнее здесь: [url]https://stackoverflow.com/questions/78835691/how-can-i-make-an-ajax-call-asynchronously-from-javascript-to-mvc-controller-met[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия