mvc ajax call example :
JQuery AJAX with ASP.NET MVC :
View
<div id="InfoModalColor" class="modal-header">
<h4 class="modal-title">CHANGE PASSWORD</h4>
</div>
<div class="modal-body">
<label for="exampleInputEmail1">Old Password</label>
<input type="password" class="form-control bg-info-form" id="txtCurrentPassword">
<br clear="all" />
<label for="exampleInputPassword1">New Password</label>
<input type="password" class="form-control bg-info-form" id="txtNewPassword">
<br clear="all" />
<label for="exampleInputPassword1">Retype New Password</label>
<input type="password" class="form-control bg-info-form" id="txtRetryPassword">
<br clear="all" />
</div>
<div class="modal-footer">
//Button Call
<span id="lblError" style="color:red;float: left" ></span>
<button type="button" id="btnSave" class="btn btn-info" data-toggle="modal">Save changes</button>
</div>
JQuery :
$(document).ready(function () {
$('#btnSave').click(function () {
//Function Name
changePassword();
});
});
function changePassword() {
var currentPassword = $("#txtCurrentPassword").val();
var newPassword = $("#txtNewPassword").val();
var retypePassword = $("#txtRetryPassword").val();
var userId = $("#txtUserId").val();
//Data JQuery URL Passed Parameters
var data = {
"userId": userId,
"currentPassword": currentPassword,
"newPassword": newPassword
};
$.ajax({
//passed URL :
url: '@Url.Content("~/UserSetting/changePassword")',
type: "POST",
data: JSON.stringify(data),
dataType: "json",
contentType: "application/json",
success: function (data) {
console.log(data);
if (data.success == true) {
$('#txtCurrentPassword').val('');
$('#txtNewPassword').val('');
$('#txtRetryPassword').val('');
$('#SuccessModalColor').modal('show');
}
else {
$('#lblError').text("Current password not correct");
$('#SuccessModalColor').modal('hide');
}
},
error: function () {
}
});
}
//Controller
//Method Name
//
[HttpPost]
public JsonResult changePassword(UserPasswordchange objChangePassword)
{
try
{
db = new AdminContext();
var userProfile = db.GetBy<User>(x => x.id == objChangePassword.userId && x.passcode==objChangePassword.currentPassword);
if (userProfile != null)
{
userProfile.passcode = objChangePassword.newPassword;
userProfile = db.Update<User>(userProfile);
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
else
{
return Json(new { success = false }, JsonRequestBehavior.AllowGet);
}
}
catch
{
return Json(new { success = false }, JsonRequestBehavior.AllowGet);
}
}
//Model
public class UserPasswordchange
{
public long userId { get; set; }
public string currentPassword { get; set; }
public string newPassword { get; set; }
}
No comments:
Post a Comment