Header Ads

ASP.NET MVC5: Razor Ajax Form Control

Razor View Engine offers many UI controls that ease out processing of many UI components when using integration with server side. Ajax form control is one of many UI controls which is being offered by razor view engine.


Today, I shall be demonstrating 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 ASP.NET MVC5.
  2. Knowledge of 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.

Download Now!

Let's begin now.  

1) Create a new MVC project and name it "RazorAjaxControl".
2) Open the file "Views\Shared\_Layout.cshtml" file and replace following code 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 &copy; @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 above code, we have simply added our basic layout.

3) Now 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" then search for jquery.unobtrusive-ajax library and install this library into your project as shown below i.e.


4) Now, open "App_Start\BundleConfig.cs" file and add "jquery.unobtrusive-ajax.js" file reference in it by replacing below code i.e.


using System.Web;
using System.Web.Optimization;

namespace RazorAjaxControl
{
    public class BundleConfig
    {
        // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));

            // Jquery validator & unobstrusive ajax
            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"));

            // Use the development version of Modernizr to develop with and learn from. Then, when you're
            // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
            bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                        "~/Scripts/modernizr-*"));

            bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                      "~/Scripts/bootstrap.js",
                      "~/Scripts/respond.js"));

            // Custom Form
            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 above configuration file, we have simply add require javascript and CSS style sheet files references in to our project.  

5) Now create a new controller and name it "Controllers\RazorAjaxController.cs" and replace following code in it i.e.


//-----------------------------------------------------------------------
// <copyright file="RazorAjaxController.cs" company="None">
//     Copyright (c) Allow to distribute this code.
// </copyright>
// <author>Asma Khalid</author>
//-----------------------------------------------------------------------

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;

    /// <summary>
    /// Ajax razor controller class.
    /// </summary>
    public class RazorAjaxController : Controller
    {
        #region Index view method.

        #region Get: /RazorAjax/Index method.

        /// <summary>
        /// Get: /RazorAjax/Index method.
        /// </summary>        
        /// <returns>Return index view</returns>
        public ActionResult Index()
        {
            try
            {
            }
            catch (Exception ex)
            {
                // Info
                Console.Write(ex);
            }

            // Info.
            return this.View();
        }

        #endregion

        #region POST: /RazorAjax/Index

        /// <summary>
        /// POST: /RazorAjax/Index
        /// </summary>
        /// <param name="model">Model parameter</param>
        /// <returns>Return - RazorAjax content</returns>
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Index(RazorAjaxViewModel model)
        {
            try
            {
                // Verification
                if (ModelState.IsValid)
                {
                    // Info.
                    return this.Json(new { EnableSuccess = true, SuccessTitle = "Success", SuccessMsg = model.Text });
                }
            }
            catch (Exception ex)
            {
                // Info
                Console.Write(ex);
            }

            // Info
            return this.Json(new { EnableError = true, ErrorTitle = "Error", ErrorMsg = "Something goes wrong, please try again later" });
        }

        #endregion

        #endregion
    }
}

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

6) Create "Models\RazorAjaxtViewModels.cs" model file and replace following code in it i.e.


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 above code, we have created our simple view model to attach it to our UI.  

7) Now, create a new file "Views\RazorAjax\Index.cshtml" and replace following code in it i.e.


@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 above code we have created a razor view engine control i.e. ajax form control with following line of code i.e.


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

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

8) Now, create a JavaScript file "Scripts\custom-form.js" and replace following code in it i.e.


$(document).ready(function ()
{
    $("#AjaxformId").submit(function (event)
    {
        var dataString;
        event.preventDefault();
        event.stopImmediatePropagation();
        var action = $("#AjaxformId").attr("action");

        // Setting.
        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)
            {
                // Result.
                onAjaxRequestSuccess(result);
            },
            error: function (jqXHR, textStatus, errorThrown)
            {
                //do your own thing
                alert("fail");
            }
        });

    }); //end .submit()
});

var onAjaxRequestSuccess = function (result)
{
    if (result.EnableError)
    {
        // Setting.
        alert(result.ErrorMsg);
    }
    else if (result.EnableSuccess)
    {
        // Setting.
        alert(result.SuccessMsg);

        // Resetting form.
        $('#AjaxformId').get(0).reset();
    }
}

 In the above code, notice that we have created our ajax control "OnSuccess" method i.e. "OnAjaxRequestSuccess" and also, we have hooked Jquery form submit method, the reason for that is simple that since we are using ajax form control, on submitting the request to server, our request will be sent two times, one is sent by ajax form control and another one is send by normal form submit request, so, we have hooked the jquery submit method which ensures that our request is sent only once to the server.

9) Now, execute the project and you will be able to see following output i.e.




Conclusion

In this article, you will learn about razor view engine control i.e. ajax form control. You will also learn to use the ajax form control with asp.net mvc platform.

No comments