У меня есть проект MVC Core ASP.NET, и я пытаюсь отправить модель и какой-то другой параметр от JavaScript в действие контроллера.const urlAction = window.location.origin + "/UserAccount/ConfirmContact";
const jqXHR = $.ajax({
method: "POST",
url: urlAction,
data: { model: model, contactType: contactType },
contentType: "application/json; charset=utf-8"
});
await jqXHR?.then(
async function(data, textStatus, jqxhr)
{
alert(`request to ${urlAction} is successed`);
},
function(jqxhr, textStatus, errorThrown)
{
alert(`request to ${urlAction} is failed; status: ${textStatus}; error: ${errorThrown}`);
});
< /code>
Моя модель: < /p>
public enum ContactType : int
{
EMail = 0,
PhoneNumber
}
public class AccountViewModel : ModelBase
{
public string? UserId { get; set; }
public string? UserName { get; set; }
public string Password { get; set; }
public string PasswordConfirmation { get; set; }
public bool TwoFactorEnabled { get; set; }
public TwoFactorMethod TwoFactorMethod { get; set; }
public string? Email { get; set; }
public string? PhoneNumber { get; set; }
public ContactConfirmationState EmailConfirmationState { get; set; }
public ContactConfirmationState PhoneConfirmationState { get; set; }
public string Name { get; set; }
public string? EsiaLogin { get; set; }
public string? EsiaPassword { get; set; }
public string EsiaPasswordConfirmation { get; set; }
public AccountViewModel()
{
}
}
< /code>
На стороне контроллера: < /p>
[HttpPost]
public async Task ConfirmContact(AccountViewModel model, ContactType contactType)
{
if(model != null)
{
if(contactType == ContactType.PhoneNumber)
{
if(await PhoneConfirmationService.SendVerificationCode(model))
{
model.PhoneConfirmationState = ContactConfirmationState.AwaitingConfirmation;
}
}
else
{
if(await EmailConfirmationService.SendVerificationCode(HttpContext, model))
{
model.EmailConfirmationState = ContactConfirmationState.AwaitingConfirmation;
}
}
}
return View("Register", model ?? new AccountViewModel());
}
< /code>
Но параметры действия не инициализируются из запроса, но со значением по умолчанию.
Как правильно отправить данные? < /p>
Подробнее здесь: https://stackoverflow.com/questions/796 ... ller-using
Как отправить модель и некоторые другие параметры от JavaScript к контроллеру с помощью jQuery.ajax? ⇐ Javascript
Форум по Javascript
1752177488
Anonymous
У меня есть проект MVC Core ASP.NET, и я пытаюсь отправить модель и какой-то другой параметр от JavaScript в действие контроллера.const urlAction = window.location.origin + "/UserAccount/ConfirmContact";
const jqXHR = $.ajax({
method: "POST",
url: urlAction,
data: { model: model, contactType: contactType },
contentType: "application/json; charset=utf-8"
});
await jqXHR?.then(
async function(data, textStatus, jqxhr)
{
alert(`request to ${urlAction} is successed`);
},
function(jqxhr, textStatus, errorThrown)
{
alert(`request to ${urlAction} is failed; status: ${textStatus}; error: ${errorThrown}`);
});
< /code>
Моя модель: < /p>
public enum ContactType : int
{
EMail = 0,
PhoneNumber
}
public class AccountViewModel : ModelBase
{
public string? UserId { get; set; }
public string? UserName { get; set; }
public string Password { get; set; }
public string PasswordConfirmation { get; set; }
public bool TwoFactorEnabled { get; set; }
public TwoFactorMethod TwoFactorMethod { get; set; }
public string? Email { get; set; }
public string? PhoneNumber { get; set; }
public ContactConfirmationState EmailConfirmationState { get; set; }
public ContactConfirmationState PhoneConfirmationState { get; set; }
public string Name { get; set; }
public string? EsiaLogin { get; set; }
public string? EsiaPassword { get; set; }
public string EsiaPasswordConfirmation { get; set; }
public AccountViewModel()
{
}
}
< /code>
На стороне контроллера: < /p>
[HttpPost]
public async Task ConfirmContact(AccountViewModel model, ContactType contactType)
{
if(model != null)
{
if(contactType == ContactType.PhoneNumber)
{
if(await PhoneConfirmationService.SendVerificationCode(model))
{
model.PhoneConfirmationState = ContactConfirmationState.AwaitingConfirmation;
}
}
else
{
if(await EmailConfirmationService.SendVerificationCode(HttpContext, model))
{
model.EmailConfirmationState = ContactConfirmationState.AwaitingConfirmation;
}
}
}
return View("Register", model ?? new AccountViewModel());
}
< /code>
Но параметры действия не инициализируются из запроса, но со значением по умолчанию.
Как правильно отправить данные? < /p>
Подробнее здесь: [url]https://stackoverflow.com/questions/79697546/how-to-send-model-and-some-other-parameters-from-javascript-to-controller-using[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия