ASP.NET MVC 5 - Razor AJAX Form Control

Razor View Engine offers many UI controls, which eases the processing of many UI components when using an integration with the Server side. AJAx form control is one of many UI controls, which is being offered by Razor View engine.

 
Today, I shall be demonstrating the usage of Razor view engine control i.e. "AJAX Form" control with ASP.NET MVC5 platform.

Following are some prerequisites before you proceed further in this tutorial.

  1. Knowledge of an ASP.NET MVC5.
  2. Knowledge of an HTML.
  3. Knowledge of JavaScript.
  4. Knowledge of Bootstrap.
  5. Knowledge of jQuery.
  6. Knowledge of C# programming.

You can download the complete source code for this tutorial or you can follow the step by step discussion below. The sample code is being developed in Microsoft Visual Studio 2015 Enterprise.

Let's begin now.

Step 1

Create a new MVC project and name it RazorAjaxControl.

Step 2

Open Views\Shared\_Layout.cshtml file and replace the code given below in it i.e.

  1. <!DOCTYPE html>  
  2. <html>  
  3.   
  4. <head>  
  5.     <meta charset="utf-8" />  
  6.     <meta name="viewport" content="width=device-width, initial-scale=1.0">  
  7.     <title>@ViewBag.Title</title> @Styles.Render("~/Content/css") @Scripts.Render("~/bundles/modernizr")  
  8.     <!-- Font Awesome -->  
  9.     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" />  
  10.     <!-- Button Loader -->@Styles.Render("~/Plugin/Ladda-loader/css") </head>  
  11.   
  12. <body>  
  13.     <div class="navbar navbar-inverse navbar-fixed-top">  
  14.         <div class="container">  
  15.             <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">  
  16. <span class="icon-bar"></span>  
  17. <span class="icon-bar"></span>  
  18. <span class="icon-bar"></span>  
  19. </button> </div>  
  20.         </div>  
  21.     </div>  
  22.     <div class="container body-content"> @RenderBody()  
  23.         <hr />  
  24.         <footer>  
  25.             <center>  
  26.                 <p><strong>Copyright © @DateTime.Now.Year - <a href="http://wwww.asmak9.com/">Asma's Blog</a>.</strong> All rights reserved.</p>  
  27.             </center>  
  28.         </footer>  
  29.     </div> @*Scripts*@ @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/jqueryval") @Scripts.Render("~/bundles/bootstrap")  
  30.     <!-- Custom Form -->@Scripts.Render("~/scripts/custom-form") @RenderSection("scripts", required: false) </body>  
  31.   
  32. </html>  

In the code given above, we have simply added our basic layout.

Step 3

Before we move further in this tutorial, we need to first add jquery.unobtrusive-ajax.js library. To add this library, go to Tools->NuGet Package Manager->Manage NuGet Packages for Solution, followed by searching for jquery.unobtrusive-ajax library and install this library into your project, as shown below.

 

Step 4

Now, open App_Start\BundleConfig.cs file and add jquery.unobtrusive-ajax.js file reference in it by replacing the code given below i.e.
  1. using System.Web;  
  2. using System.Web.Optimization;  
  3. namespace RazorAjaxControl {  
  4.     public class BundleConfig {  
  5.         // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862  
  6.         public static void RegisterBundles(BundleCollection bundles) {  
  7.             bundles.Add(new ScriptBundle("~/bundles/jquery").Include("~/Scripts/jquery-{version}.js"));  
  8.             // Jquery validator & unobstrusive ajax  
  9.             bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include("~/Scripts/jquery.unobtrusive-ajax.js""~/Scripts/jquery.unobtrusive-ajax.min.js""~/Scripts/jquery.validate*""~/Scripts/jquery.validate.unobtrusive.js""~/Scripts/jquery.validate.unobtrusive.min.js"));  
  10.             // Use the development version of Modernizr to develop with and learn from. Then, when you're  
  11.             // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.  
  12.             bundles.Add(new ScriptBundle("~/bundles/modernizr").Include("~/Scripts/modernizr-*"));  
  13.             bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include("~/Scripts/bootstrap.js""~/Scripts/respond.js"));  
  14.             // Custom Form  
  15.             bundles.Add(new ScriptBundle("~/scripts/custom-form").Include("~/Scripts/custom-form.js"));  
  16.             bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/bootstrap.css""~/Content/site.css"));  
  17.         }  
  18.     }  
  19. }  

In the configuration file given above, we have to simply add the required JavaScript and CSS style sheet files references in to our project.

Step 5

Now, create a new controller and name it Controllers\RazorAjaxController.cs and replace the code given below in it i.e.

  1. //-----------------------------------------------------------------------  
  2. // <copyright file="RazorAjaxController.cs" company="None">  
  3. // Copyright (c) Allow to distribute this code.  
  4. // </copyright>  
  5. // <author>Asma Khalid</author>  
  6. //-----------------------------------------------------------------------  
  7. namespace RazorAjaxControl.Controllers {  
  8.     using System;  
  9.     using System.Collections.Generic;  
  10.     using System.Linq;  
  11.     using System.Security.Claims;  
  12.     using System.Threading;  
  13.     using System.Threading.Tasks;  
  14.     using System.Web;  
  15.     using System.Web.Mvc;  
  16.     using Models;  
  17.     /// <summary>  
  18.     /// Ajax razor controller class.  
  19.     /// </summary>  
  20.     public class RazorAjaxController: Controller {#  
  21.         region Index view method.#region Get: /RazorAjax/Index  
  22.         method.  
  23.         /// <summary>  
  24.         /// Get: /RazorAjax/Index method.  
  25.         /// </summary>  
  26.         /// <returns>Return index view</returns>  
  27.         public ActionResult Index() {  
  28.             try {} catch (Exception ex) {  
  29.                 // Info  
  30.                 Console.Write(ex);  
  31.             }  
  32.             // Info.  
  33.             return this.View();  
  34.         }#  
  35.         endregion# region POST: /RazorAjax/Index  
  36.         /// <summary>  
  37.         /// POST: /RazorAjax/Index  
  38.         /// </summary>  
  39.         /// <param name="model">Model parameter</param>  
  40.         /// <returns>Return - RazorAjax content</returns>  
  41.         [HttpPost]  
  42.         [AllowAnonymous]  
  43.         [ValidateAntiForgeryToken]  
  44.         public ActionResult Index(RazorAjaxViewModel model) {  
  45.             try {  
  46.                 // Verification  
  47.                 if (ModelState.IsValid) {  
  48.                     // Info.  
  49.                     return this.Json(new {  
  50.                         EnableSuccess = true, SuccessTitle = "Success", SuccessMsg = model.Text  
  51.                     });  
  52.                 }  
  53.             } catch (Exception ex) {  
  54.                 // Info  
  55.                 Console.Write(ex);  
  56.             }  
  57.             // Info  
  58.             return this.Json(new {  
  59.                 EnableError = true, ErrorTitle = "Error", ErrorMsg = "Something goes wrong, please try again later"  
  60.             });  
  61.         }#  
  62.         endregion# endregion  
  63.     }  
  64. }  

In the code given above, I have simply created HTTP GET & HTTP POST methods. The HTTP POST method above will return a JSON package with our input text.

Step 6

Create Models\RazorAjaxtViewModels.cs model file and replace the code given below in it.

  1. using System.Collections.Generic;  
  2. using System.ComponentModel.DataAnnotations;  
  3. namespace RazorAjaxControl.Models {  
  4.     public class RazorAjaxViewModel {  
  5.         [Required]  
  6.         [Display(Name = "Text")]  
  7.         public string Text {  
  8.             get;  
  9.             set;  
  10.         }  
  11.     }  
  12. }  

In the code given above, we have created our simple view model to attach it to our UI.

Step 7

Now, create a new file Views\RazorAjax\Index.cshtml and replace the code given below in it.

  1. @using RazorAjaxControl.Models  
  2. @model RazorAjaxControl.Models.RazorAjaxViewModel  
  3. @{  
  4. ViewBag.Title = "ASP.NET MVC5: Razor Ajax Form Comtrol";  
  5. }  
  6.    <div class="row">  
  7.    <div class="panel-heading">  
  8.    <div class="col-md-8">  
  9. <h3>  
  10.    <i class="fa fa-file-text-o"></i>  
  11.    <span>ASP.NET MVC5: Razor Ajax Form Control</span>  
  12. </h3>  
  13. </div>  
  14. </div>  
  15. </div>  
  16.    <div class="row">  
  17.    <section class="col-md-4 col-md-push-4">  
  18.    @using (Ajax.BeginForm("Index""RazorAjax"new AjaxOptions { HttpMethod = "POST", OnSuccess = "onAjaxRequestSuccess" }, new { @id =    "AjaxformId", @class = "form-horizontal", role = "form" }))  
  19.    {  
  20.       @Html.AntiForgeryToken()  
  21.       <div class="well bs-component">  
  22.       <br />  
  23.       <div class="row">  
  24.       <div class="col-md-12 col-md-push-2">  
  25.       <div class="form-group">  
  26.       <div class="col-md-10 col-md-pull-1">  
  27. @Html.TextBoxFor(m => m.Text, new { placeholder = Html.DisplayNameFor(m => m.Text), @class = "form-control" })  
  28. @Html.ValidationMessageFor(m => m.Text, ""new { @class = "text-danger custom-danger" })  
  29.       </div>  
  30.       </div>  
  31. <div class="form-group">  
  32.       <div class="col-md-18">  
  33.          </div>  
  34.             </div>  
  35.             <div class="form-group">  
  36.             <div class="col-md-4 col-md-push-2">  
  37.          <div>  
  38. <button type="submit"  
  39.       class="btn btn-warning"  
  40.       value="Process">  
  41.       <span class="ladda-label">Process</span>  
  42. </button>  
  43.       </div>  
  44.       </div>  
  45.    </div>  
  46.    </div>  
  47.    </div>  
  48. </div>  
  49. }  
  50. </section>  
  51. </div>  

In the code given above, we have created a Razor view engine control i.e. AJAX form control with the line of code given below in it.

  1. @using (Ajax.BeginForm("Index""RazorAjax"new AjaxOptions { HttpMethod = "POST", OnSuccess = "onAjaxRequestSuccess" }, new { @id = "AjaxformId", @class = "form-horizontal", role = "form" }))  

In the line of code given above, notice the "OnSuccess" method i.e. "OnAjaxRequestSuccess". This is JavaScript method, which will be called when a request of form is being posted to the server.

Step 8

Now, create a JavaScript file Scripts\custom-form.js and replace the code given below.

  1. $(document).ready(function() {  
  2.     $("#AjaxformId").submit(function(event) {  
  3.         var dataString;  
  4.         event.preventDefault();  
  5.         event.stopImmediatePropagation();  
  6.         var action = $("#AjaxformId").attr("action");  
  7.         // Setting.  
  8.         dataString = new FormData($("#AjaxformId").get(0));  
  9.         contentType = false;  
  10.         processData = false;  
  11.         $.ajax({  
  12.             type: "POST",  
  13.             url: action,  
  14.             data: dataString,  
  15.             dataType: "json",  
  16.             contentType: contentType,  
  17.             processData: processData,  
  18.             success: function(result) {  
  19.                 // Result.  
  20.                 onAjaxRequestSuccess(result);  
  21.             },  
  22.             error: function(jqXHR, textStatus, errorThrown) {  
  23.                 //do your own thing  
  24.                 alert("fail");  
  25.             }  
  26.         });  
  27.     }); //end .submit()  
  28. });  
  29. var onAjaxRequestSuccess = function(result) {  
  30.     if (result.EnableError) {  
  31.         // Setting.  
  32.         alert(result.ErrorMsg);  
  33.     } else if (result.EnableSuccess) {  
  34.         // Setting.  
  35.         alert(result.SuccessMsg);  
  36.         // Resetting form.  
  37.         $('#AjaxformId').get(0).reset();  
  38.     }  
  39. }  

In the code given above, notice that we have created our AJAX control "OnSuccess" method i.e. "OnAjaxRequestSuccess" and also, we have hooked jQuery form submit method and the reason for this is simple, since we are using AJAX form control. On submitting the request to the Server, our request will be sent two times, where one is sent by AJAX form control and another one is sent by normal form submit request, so we have hooked jQuery submit method, which ensures that our request is sent only once to the Server.

Step 9

Now, execute the project and you will be able to see the output given below.

 


Conclusion

In this article, you learned about Razor view engine control i.e. AJAX form control. You will also learn to use AJAX form control with an ASP.NET MVC platform.

Up Next
    Ebook Download
    View all
    Learn
    View all