У меня есть проект ASP.net Core MVC, и я пытаюсь отправить модель и какой -то другой параметр от JavaScript в действие контроллера. Сначала я заполняю модель из полей просмотра, имена которых соответствуют свойствам модели.var model = {}; //global variable
function updateModel()
{
for(const element of document.querySelectorAll("input.account-property-input"))
{
if(element instanceof HTMLInputElement && typeof element.name === "string" && element.name.trim().length > 0)
{
model[element.name] = element.value;
}
}
let checkbox = document.querySelector("input#enable-two-factor-checkbox");
if(checkbox instanceof HTMLInputElement)
{
model[checkbox.name] = checkbox.checked;
}
if(checkbox.checked)
{
radio = document.querySelector("input#two-factor-by-phone-radio");
model.TwoFactorMethod = radio.checked ? "TwoFactorByPhoneNumber" : "TwoFactorByEmail";
}
}
< /code>
Отправка данных: < /p>
model = updateModel();
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>
Но параметры действия не инициализируются не из запроса, но со значением по умолчанию.
Как правильно отправить данные?
My Project Repo < /p>
Подробнее здесь: https://stackoverflow.com/questions/796 ... ller-using
Как отправить модель и некоторые другие параметры от JavaScript к контроллеру с помощью jQuery.ajax? ⇐ C#
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение