Best way to submit from using Ajax post method in ASP.NET MVC
jQuery Code :
function Login() {
debugger;
var hasError = Validate("#divUserLoginContainer");
if (!hasError) {
var url = '/UserLogin/SignIn';
}
$.post(url, $('#frmUserLogin').serialize(), function (data) {
if (data.isSuccess == true) {
debugger;
swal({
title: "Success",
text: data.message,
icon: "success",
})
.then((refresh) => {
alert("")
window.location.href = '/Employer/EmployerSubscription/Index';
});
}
else {
swal("Oops", data.message, "error");
}
});
};
debugger;
var hasError = Validate("#divUserLoginContainer");
if (!hasError) {
var url = '/UserLogin/SignIn';
}
$.post(url, $('#frmUserLogin').serialize(), function (data) {
if (data.isSuccess == true) {
debugger;
swal({
title: "Success",
text: data.message,
icon: "success",
})
.then((refresh) => {
alert("")
window.location.href = '/Employer/EmployerSubscription/Index';
});
}
else {
swal("Oops", data.message, "error");
}
});
};
Html Code
<div class="container">
<div class="row">
<div class="col-md-6">
<div id="#divUserLoginContainer">
<form method="post" asp-action="SignIn" asp-controller="UserLogin" class="box" id="frmUserLogin">
@Html.AntiForgeryToken()
<h1>Login</h1>
<p class="text-muted"> Please enter your login and password!</p>
<input type="text" asp-for="Email" name="Email" placeholder="Enter email" class="requiredField">
<input type="password" asp-for="Password" name="Password" placeholder="Enter Password" class="requiredField">
<input type="button" name="" class="btn btn-primary pull-center" onclick="javascript:Login();" value="Login">
<br />
<a class="forgot text-muted" asp-area="" asp-controller="User" asp-action="ForgotPassword">Forgot password?</a><br />
<a class="forgot text-muted" asp-area="" asp-controller="User" asp-action="Registration">Register</a>
</form>
</div>
</div>
</div>
</div>
Require scripts :
<link href="~/css/Login.css" rel="stylesheet" />
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.0.3/css/font-awesome.css" />
<script src="~/js/validation/custom-validation.js"></script>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
ActionResult Method
public async Task<IActionResult> SignIn(UserLoginViewModel model)
{
if (!ModelState.IsValid)
{
_returnModel.Message = ModelState.FirstOrDefault(x => x.Value.Errors.Any()).Value.Errors.FirstOrDefault().ErrorMessage;
return Json(_returnModel);
}
_returnModel = await _userLoginService.UserLogin(model);
if (_returnModel.IsSuccess)
{
var result = (UserEntity)_returnModel.Data;
TempData["UserId"] = result.Id.ToString();
}
return Json(_returnModel);
}
Comments
Post a Comment