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.
- Knowledge of an ASP.NET MVC5.
- Knowledge of an HTML.
- Knowledge of JavaScript.
- Knowledge of Bootstrap.
- Knowledge of jQuery.
- 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.
- <!DOCTYPE html>
- <html>
-
- <head>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>@ViewBag.Title</title> @Styles.Render("~/Content/css") @Scripts.Render("~/bundles/modernizr")
- <!-- Font Awesome -->
- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" />
- <!-- Button Loader -->@Styles.Render("~/Plugin/Ladda-loader/css") </head>
-
- <body>
- <div class="navbar navbar-inverse navbar-fixed-top">
- <div class="container">
- <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
- <span class="icon-bar"></span>
- <span class="icon-bar"></span>
- <span class="icon-bar"></span>
- </button> </div>
- </div>
- </div>
- <div class="container body-content"> @RenderBody()
- <hr />
- <footer>
- <center>
- <p><strong>Copyright © @DateTime.Now.Year - <a href="http://wwww.asmak9.com/">Asma's Blog</a>.</strong> All rights reserved.</p>
- </center>
- </footer>
- </div> @*Scripts*@ @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/jqueryval") @Scripts.Render("~/bundles/bootstrap")
- <!-- Custom Form -->@Scripts.Render("~/scripts/custom-form") @RenderSection("scripts", required: false) </body>
-
- </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.
- using System.Web;
- using System.Web.Optimization;
- namespace RazorAjaxControl {
- public class BundleConfig {
-
- public static void RegisterBundles(BundleCollection bundles) {
- bundles.Add(new ScriptBundle("~/bundles/jquery").Include("~/Scripts/jquery-{version}.js"));
-
- 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"));
-
-
- bundles.Add(new ScriptBundle("~/bundles/modernizr").Include("~/Scripts/modernizr-*"));
- bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include("~/Scripts/bootstrap.js", "~/Scripts/respond.js"));
-
- bundles.Add(new ScriptBundle("~/scripts/custom-form").Include("~/Scripts/custom-form.js"));
- bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/bootstrap.css", "~/Content/site.css"));
- }
- }
- }
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.
-
-
-
-
-
-
- namespace RazorAjaxControl.Controllers {
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Security.Claims;
- using System.Threading;
- using System.Threading.Tasks;
- using System.Web;
- using System.Web.Mvc;
- using Models;
-
-
-
- public class RazorAjaxController: Controller {#
- region Index view method.#region Get: /RazorAjax/Index
- method.
-
-
-
-
- public ActionResult Index() {
- try {} catch (Exception ex) {
-
- Console.Write(ex);
- }
-
- return this.View();
- }#
- endregion# region POST: /RazorAjax/Index
-
-
-
-
-
- [HttpPost]
- [AllowAnonymous]
- [ValidateAntiForgeryToken]
- public ActionResult Index(RazorAjaxViewModel model) {
- try {
-
- if (ModelState.IsValid) {
-
- return this.Json(new {
- EnableSuccess = true, SuccessTitle = "Success", SuccessMsg = model.Text
- });
- }
- } catch (Exception ex) {
-
- Console.Write(ex);
- }
-
- return this.Json(new {
- EnableError = true, ErrorTitle = "Error", ErrorMsg = "Something goes wrong, please try again later"
- });
- }#
- endregion# endregion
- }
- }
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.
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
- namespace RazorAjaxControl.Models {
- public class RazorAjaxViewModel {
- [Required]
- [Display(Name = "Text")]
- public string Text {
- get;
- set;
- }
- }
- }
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.
- @using RazorAjaxControl.Models
- @model RazorAjaxControl.Models.RazorAjaxViewModel
- @{
- ViewBag.Title = "ASP.NET MVC5: Razor Ajax Form Comtrol";
- }
- <div class="row">
- <div class="panel-heading">
- <div class="col-md-8">
- <h3>
- <i class="fa fa-file-text-o"></i>
- <span>ASP.NET MVC5: Razor Ajax Form Control</span>
- </h3>
- </div>
- </div>
- </div>
- <div class="row">
- <section class="col-md-4 col-md-push-4">
- @using (Ajax.BeginForm("Index", "RazorAjax", new AjaxOptions { HttpMethod = "POST", OnSuccess = "onAjaxRequestSuccess" }, new { @id = "AjaxformId", @class = "form-horizontal", role = "form" }))
- {
- @Html.AntiForgeryToken()
- <div class="well bs-component">
- <br />
- <div class="row">
- <div class="col-md-12 col-md-push-2">
- <div class="form-group">
- <div class="col-md-10 col-md-pull-1">
- @Html.TextBoxFor(m => m.Text, new { placeholder = Html.DisplayNameFor(m => m.Text), @class = "form-control" })
- @Html.ValidationMessageFor(m => m.Text, "", new { @class = "text-danger custom-danger" })
- </div>
- </div>
- <div class="form-group">
- <div class="col-md-18">
- </div>
- </div>
- <div class="form-group">
- <div class="col-md-4 col-md-push-2">
- <div>
- <button type="submit"
- class="btn btn-warning"
- value="Process">
- <span class="ladda-label">Process</span>
- </button>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- }
- </section>
- </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.
- @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.
- $(document).ready(function() {
- $("#AjaxformId").submit(function(event) {
- var dataString;
- event.preventDefault();
- event.stopImmediatePropagation();
- var action = $("#AjaxformId").attr("action");
-
- dataString = new FormData($("#AjaxformId").get(0));
- contentType = false;
- processData = false;
- $.ajax({
- type: "POST",
- url: action,
- data: dataString,
- dataType: "json",
- contentType: contentType,
- processData: processData,
- success: function(result) {
-
- onAjaxRequestSuccess(result);
- },
- error: function(jqXHR, textStatus, errorThrown) {
-
- alert("fail");
- }
- });
- });
- });
- var onAjaxRequestSuccess = function(result) {
- if (result.EnableError) {
-
- alert(result.ErrorMsg);
- } else if (result.EnableSuccess) {
-
- alert(result.SuccessMsg);
-
- $('#AjaxformId').get(0).reset();
- }
- }
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.