I’m encountering an issue with my controller. When I use to call the controller, it returns a new JSON page instead of processing the response within the script.
My controller looks like this:
[HttpPost]
public async Task<ActionResult> Login(LoginModel model)
{
if (ModelState.IsValid)
{
var user = await _context.Users
.FirstOrDefaultAsync(u => u.Username == model.Username && u.Password == model.Password);
if (user != null)
{
string generatedToken = TokenGenerator.GenerateRandomToken(_tokenLengthKey);
DateTime tokenExpiration = DateTime.UtcNow.AddMinutes(_tokenLifetimeMinutes);
// Update user with new token and expiration
user.Token = generatedToken;
user.TokenExpiresAt = tokenExpiration;
// Save Token and TokenExpiresAt to the database
_context.Entry(user).State = EntityState.Modified;
await _context.SaveChangesAsync();
Session["Username"] = user.Username;
Session["Name"] = user.Name;
// Redirect to home page
return Json(new { success = false, redirectUrl = Url.Action("Index", "Home") });
}
else
{
return Json(new { success = false, redirectUrl = Url.Action("Login", "Account") });
}
}
return Json(new { error = "model is invalid" });
}
And my script looks like this:
<script type="text/javascript">
$(document).ready(function () {
$('#loginForm').submit(function (e) {
e.preventDefault();
$.ajax({
url: '@Url.Action("Login", "Account")',
type: 'POST',
data: $(this).serialize(),
success: function (response) {
if (response.success) {
window.location.href = response.redirectUrl;
} else if (response.error) {
$('#errorMessage').text(response.error).removeClass('d-none');
}
},
error: function (xhr, status, error) {
console.error("Error:", status, error);
}
});
});
});
</script>
I want the JSON response to be processed within the script instead of displaying a new page.
New contributor
Anh Trung is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.