I have made a form in my .NET MVC 5 application like following:
@using (Ajax.BeginForm("ChangePassword", "User", new { area = "UserSettings" }, new
AjaxOptions
{
HttpMethod = "POST",
OnSuccess = "alert('success');" //This will execute once the Ajax call is finished.
}, null))
{
@Html.TextBoxFor(m => m.Password, new { placeholder = "Password", @class = "form-control", @type = "password" })<br />
@Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger", @style = "float:right;" })
@Html.TextBoxFor(m => m.PasswordConfirm, new { placeholder = "Confirm password", @class = "form-control", @type = "password" })<br />
@Html.ValidationMessageFor(model => model.PasswordConfirm, "", new { @class = "text-danger", @style = "float:right;" })
<button type="submit" class="btn btn-primary">Change Password</button>
}
And this is the method in controller:
[HttpPost]
[ActionName("ChangePassword")]
public ActionResult ChangePassword(UserSettings model)
{
using (var ctx = new myContextEntities())
{
var usr = ctx.Users.FirstOrDefault(x => x.Email == User.Identity.Name);
model.FirstName = usr.FirstName;
model.LastName = usr.LastName;
model.Email = usr.Email;
model.Country = usr.Countries.CountryName;
if (ModelState.IsValid)
{
usr.PasswordSalt = Helpers.PasswordHelper.CreateSalt(40);
usr.PasswordHash = Helpers.PasswordHelper.CreatePasswordHash(model.Password, usr.PasswordSalt);
ctx.SaveChanges();
return View("UserSettings",model);
}
return View("UserSettings", model);
}
}
Once the call is finished the page just refreshes, which shouldn't happen, but it should rather just display the success message ... ? What am I doing wrong here?
For Ajax request, please create the following bundle in BundleConfig.cs
public static void RegisterBundles(BundleCollection bundles)
{
//Create Your other bundles here
//Create your Jquery validate bundle
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/Assets/jquery.validate.min.js",
"~/Scripts/Assets/jquery.validate.unobtrusive.min.js",
"~/Scripts/Assets/jquery.unobtrusive-ajax.min.js"
));
}
In your _Layout.cshtml. Include this bundle as:
@Scripts.Render("~/bundles/jqueryval")
Please make sure, jQuery must be included before this bundle. Please note that the paths to the javascript files are dummy in the above code block. You should give your own paths. The following JS files must be included:
Hope it helps :)
Include Unobtrusive Ajax from the below Link
Note: Dont include both jquery.unobtrusive-ajax.min.js and jquery.unobtrusive-ajax.min.js, Include only one (js/min.js) file
The Below Files Does not Affect anything for you and your problem..
1.jquery.validate.min.js
2.jquery.validate.unobtrusive.min.js