Wednesday, 30 January 2019

MVC Ajax.BeginForm

In MVC, Ajax.BeginForm provides the way to submit the form asynchrounsly. Follow the following simple steps to achieve submit form using Ajax.BeginForm in MVC.


Step 1: Include following js libraries in your view page:
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

If you didn't find these files in your solution then you can easily download these using nuget manager.

Step 2: Add ajax form in your view as following:

@using (Ajax.BeginForm("Login", "Account", null, new AjaxOptions { OnSuccess = "success", OnFailure = "failure", OnBegin = "showLoadingInForm(this)", OnComplete = "hideLoadingInForm(this)" }, new { id = "formLogin", @class = "form-horizontal" }))
{
<div class="form-group">
<label for="email" class="col-sm-2 control-label">
Email
</label>
<div class="col-sm-12">
<input type="email" class="form-control" name="Email" placeholder="Email" data-val="true" required />
</div>
</div>
<div class="form-group">
<label for="exampleInputPassword1" class="col-sm-2 control-label">
Password
</label>
<div class="col-sm-12">
<input type="password" class="form-control" name="Password" placeholder="Password" data-val="true" required />
</div>
</div>
<div class="form-group">
<div class="col-sm-10">
<button type="submit" class="btn btn-primary btn-sm submit">Login</button>
<a href="javascript:openForgotPassword();">Forgot your password?</a>
</div>
</div>
<div class="form-group">
<div class="col-md-12 error" id="loginFormError">
</div>
</div>
}

Step 3: Include following js functions. The above ajax form using these js functions to complete the request.
<script>
function success(response) {
if (response.Success) {
window.location.href = "/";
} else {
$("#loginFormError").text(response.Message);
}
},
function failure(response) {
$("#loginFormError").text(response.statusText);
}
function showLoadingInForm(form){
// Code to show loading
}
function hideLoadingInForm(form){
//Code to hide loading
}
</script>

Step 4: Write a server side method in your controller as bellow:
[HttpPost]
public ActionResult Login(LoginModel model)
{
   //Do your logic here.
   return View();
}

2 comments: