Saturday, November 18, 2017

How to use SyntaxHighlighter in your website

SyntaxHighlighter is a JavaScript code that highlights programming languages codes in different colors and fonts. This helps to understand the codes when you are reading it. SyntaxHighlighter works on all programming languages and scripts like C#, asp.net, SQL, jQuery, JavaScript, php, python, etc.

Today nearly all programming tutorial websites use SyntaxHighlighter for highlighting their demo codes.

Using SyntaxHighlighter in your Website

Let us use SyntaxHighlighter for highlighting codes in a web page.

Follow the steps:

1. Include the SyntaxHighlighter Core & default theme CSS links in the page head.
<link href="http://alexgorbatchev.com/pub/sh/current/styles/shCore.css" rel="stylesheet" type="text/css" />
<link href="http://alexgorbatchev.com/pub/sh/current/styles/shThemeDefault.css" rel="stylesheet" type="text/css" />

2. Include the SyntaxHighlighter brushes (JS file links) in the page head.
<script src="http://alexgorbatchev.com/pub/sh/current/scripts/shCore.js" type="text/javascript"></script>
<script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCpp.js" type="text/javascript"></script>
<script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCSharp.js" type="text/javascript"></script>
<script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCss.js" type="text/javascript"></script>
<script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJava.js" type="text/javascript"></script>
<script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJScript.js" type="text/javascript"></script>
<script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPhp.js" type="text/javascript"></script>
<script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPython.js" type="text/javascript"></script>
<script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushRuby.js" type="text/javascript"></script>
<script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushSql.js" type="text/javascript"></script>
<script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushVb.js" type="text/javascript"></script>
<script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushXml.js" type="text/javascript"></script>
<script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPerl.js" type="text/javascript"></script>

3. Add the JavaScript function in the page head.
<script language="javascript">
    SyntaxHighlighter.all();
</script>

Now whenever you want to highlight a code, add your code inside the pre lines:

<pre class="brush: js">
//code
</pre>

In the above code I used the JS brush, you can use any of the available brushes. The information about the brushes is available here.

SyntaxHighlighter Example

Let us add 3 block of codes –for jQuery, C# and HTML.
Note - Brushes used here are js, csharp and html.

Add the below code to your page:

jQuery Code

<pre class="brush: js">
    $(document).ready(function(){
        $("p").click(function(){
            $(this).hide();
        });
    });
</pre> 

C# Code

<pre class="brush: csharp">
    public int AddNumbers(int number1, int number2)
    {
        int result = number1 + number2;
        return result;
    }
</pre>

<h3>HTML Code</h3>
<pre class="brush: html">
    <h1>My First Heading</h1>
    <p>My first paragraph.</p>
</pre>

When you open the page in the web browser this is how it will look:

























Conclusion

You can see how to code are highlighted with SyntaxHighlighter in the jQueryLoad method page.
You will love using SyntaxHighlighter in your web page like I do.  


Sunday, November 12, 2017

Reading Excel File Code in C#

In your ASP.NET website you can easily read any excel file using C# code and show its contents on a div.

For this first include the namespaces in your page:

using System.Web;
using System.Data.OleDb;

using System.Text;

Then add the Code to Read Excel File:

string path = Server.MapPath("~/Upload/myexcel.xlsx");

string excelConnectionString = @"Provider='Microsoft.ACE.OLEDB.12.0';Data Source='" + path + "';Extended Properties='Excel 12.0 Xml;HDR=NO;IMEX=1'";
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
excelConnection.Open();

string tableName = excelConnection.GetSchema("Tables").Rows[0]["TABLE_NAME"].ToString();
OleDbCommand cmd = new OleDbCommand("Select * from [" + tableName + "]", excelConnection);
StringBuilder sb = new StringBuilder();
sb.Append("<table>");

OleDbDataReader dReader = cmd.ExecuteReader();
do
{
    int count = dReader.FieldCount;
    while (dReader.Read())
    {
        sb.Append("<tr>");
        for (int i = 0; i < count; i++)
        {
            sb.Append("<td>" + dReader.GetValue(i) + "</td>");
        }
        sb.Append("</tr>");
    }
} while (dReader.NextResult());

sb.Append("</table>");
excelConnection.Close();


Explanation: In the above read excel code you can see the variable “path” contains the path of excel file in the website directory. In my case it is in the “Upload” directory which is located on the website root folder.

I used “OLEDB” drivers to read the excel file, make sure to add “HDR=NO” in the connection string extended properties so that excel file’s header columns are also read.
Finally I used the “OleDbDataReader” class to loop though every row and their columns, adding them to my “StringBuilder” object named “sb”.

The “sb” variable contains the excel records in html table format, you can show its value inside a div.

In ASP.NET Web Forms you can do like:

dataDiv.InnerHtml=sb.ToString();

In ASP.NET MVC you can do like:

First saving the sb.ToString() in ViewBag variable in Controller:

ViewBag.Result = sb.ToString();
Then in the view:
<div id="dataDiv">
    @(new HtmlString(ViewBag.Result))
</div>

This is how the excel data will be shown in the div:


Monday, August 28, 2017

The First Multithreading Program in C# to learn as a Beginner

I will teach you how to start with Multithreading in C#. Here I will build a simple program that uses Multithreading. The program starts with an entry point which is executed by the first thread and then calls a function which is executed by second thread.

Since this is a multithreading example therefore the 2nd thread will work asynchronously.


Points to Note:

1. The function will be called by a delegate. I will use the delegate’s ‘BeginInvoke method to call the function asynchronously. To receive the returned value from the function, I will use the delegate’s ‘EndInvoke’ method.

2. I will make use of ‘IAsyncResult’ interface which helps in making asynchronous operations.

The function to be called by the Delegate:

The function that will be called by the delegate is an addition function that takes 2 int values and returns the sum of them.

static int Add(int x, int y)
{
    int tid = Thread.CurrentThread.ManagedThreadId; //second thread id
    Thread.Sleep(10000);
    return x + y;
}

The Add function will be called by the 2nd thread asynchronously. The ‘tid’ variable will provide you the 2nd thread id  which will be different than that of the thread that executes the entry point.

The Entry Point:

The entry point will be a small code where I will call the ‘Add’ function through a delegate in asynchronous manner.

This is how to proceed:

a. Import the namespaces

using System.Threading;
using System;

b. Create the delegate

delegate int BinaryOp(int x, int y);

c. Entry Point Code

/*Invoke Add() on a secondary thread.*/
BinaryOp b = Add;
IAsyncResult iftAR = b.BeginInvoke(10, 20, null, null);

while (!iftAR.IsCompleted)
{
    int tid = Thread.CurrentThread.ManagedThreadId; //first thread id
    Thread.Sleep(1000);
}
// Obtain the result of the Add() method when ready.
int answer = b.EndInvoke(iftAR); // 30
/*End*/

Explanation:

First I created the delegate’s object and associated the ‘Add’ function to it.  

Then I created an object of ‘IAsyncResult’ to call the delegate’s ‘BeginInvoke’ method. I passed the 2 numbers to the first two parameters and null to the last 2 parameters.

The second thread will come into existence and will execute the ‘Add’ function.

 I have use ‘iftAR.IsCompleted’ to check when the asynchronous request (the 2nd thread returns the sum of the 2 numbers) is completed. The ‘iftAR.IsCompleted’ returns true when the asynchronous request gets completed. If it returns false then I make my first thread to sleep for 1 second.

Due to the 10 seconds sleep on the ‘Add’ method, the add method will take slightly more than 10 seconds to execute. In the meanwhile the first thread waits (see the while block).

The first thread Id which you will get on the while block will be different that the seconds thread id which you will get on the ‘Add’ function. This signifies that there are 2 threads doing our work.
The int variable ‘answer’ will return 30.

Conclusion


I hope you leaned the first Multithreading program code in this tutorial. It is a very powerful feature of C# and can be used to build high performing codes in your applications.

Tuesday, May 30, 2017

How to Bind GridView with Class instead of DataTable

You have seen many times that the GridView is bind with DataTable and wonder if you can bind it by another way. The answer is "Yes", you can bind a GridView with a Class too.

Bind GridView with Class

Let me show you how to bind your GridView using a Class.

1. First add the GridView to the Web Form.

<asp:GridView ID="gridView" runat="server"></asp:GridView>

2. Go to the CS page and create a Product Class.

class Product
    {
        public string name { get; set; }
        public string image { get; set; }
        public string categoryName { get; set; }
        public decimal price { get; set; }
    }

3. Create a function that fills the Class with dummy data.

void LoadData()
    {
        product = new List<Product>();
        product.Add(new Product() { name = "Vanheusen Women's Skirt", image = "Image/s1.jpg", categoryName = "Skirts", price = 20.89M });
        product.Add(new Product() { name = "Decot Paradise Animal Print Women's Regular Black Skirt", image = "Image/s2.jpg", categoryName = "Skirts", price = 35.59M });
        product.Add(new Product() { name = "DeeVineeTi Polka Print Women's Wrap Around White, Blue Skirt", image = "Image/s3.jpg", categoryName = "Skirts", price = 98.00M });
        product.Add(new Product() { name = "Raabta Fashion Striped Women's Pencil Black, White Skirt", image = "Image/s4.jpg", categoryName = "Skirts", price = 120.00M });
        product.Add(new Product() { name = "Ishin Solid Women's Regular Orange Skirt", image = "Image/s5.jpg", categoryName = "Skirts", price = 115.85M });
        product.Add(new Product() { name = "Adidas Women's Skirt", image = "Image/s6.jpg", categoryName = "Skirts", price = 105.74M });

        product.Add(new Product() { name = "V Dot by Van Huesen Skinny Fit Men's Grey Trousers", image = "Image/p1.jpg", categoryName = "Pants", price = 10.89M });
        product.Add(new Product() { name = "French Connection Slim Fit Men's Beige Trousers", image = "Image/p2.jpg", categoryName = "Pants", price = 25.59M });
        product.Add(new Product() { name = "Indian Terrain Slim Fit Men's White Trousers", image = "Image/p3.jpg", categoryName = "Pants", price = 48.00M });
        product.Add(new Product() { name = "United Colors of Benetton Slim Fit Men's Beige Trousers", image = "Image/p4.jpg", categoryName = "Pants", price = 120.00M });
        product.Add(new Product() { name = "Numero Uno Slim Fit Men's Black Trousers", image = "Image/p5.jpg", categoryName = "Pants", price = 155.85M });
        product.Add(new Product() { name = "John Players Slim Fit Men's Grey Trousers", image = "Image/p6.jpg", categoryName = "Pants", price = 165.74M });

        product.Add(new Product() { name = "Vu 140cm (55) Full HD Smart LED TV", image = "Image/e1.png", categoryName = "Electronics", price = 80.89M });
        product.Add(new Product() { name = "BPL Vivid 80cm (32) HD Ready LED TV", image = "Image/e2.png", categoryName = "Electronics", price = 235.59M });
        product.Add(new Product() { name = "Moto E3 Power (Black, 16 GB)", image = "Image/e3.jpg", categoryName = "Electronics", price = 198.00M });
        product.Add(new Product() { name = "Krishna M (Silver, 64 GB)", image = "Image/e4.jpg", categoryName = "Electronics", price = 120.00M });
        product.Add(new Product() { name = "Sansui 150 L Direct Cool Single Door Refrigerator", image = "Image/e5.jpg", categoryName = "Electronics", price = 115.85M });
        product.Add(new Product() { name = "Whirlpool 245 L Frost Free Double Door Refrigerator", image = "Image/e6.jpg", categoryName = "Electronics", price = 105.74M });
    }

4. Fill the class with data.

LoadData();

5. Now finally bind the GridView with the class data like this:

gridView.DataSource = product;
gridView.DataBind();


Binding GridView with Class on Page Load Event
Here I will show you how to bind the GridView on Page Load event.

Add the below code to the .cs page.

List<Product> product;
protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack)
    {
        LoadData();
        gridView.DataSource = product;
        gridView.DataBind();
    }
}

void LoadData()
{
    //code
}

class Product
{
    public string name { get; set; }
    public string image { get; set; }
    public string categoryName { get; set; }
    public decimal price { get; set; }
}

and that's it the Binding of GridView is done.

Related Article: Also check the related article which teaches the 'Binding of GridView with Paging using jQuery Load with No Page Refresh'. Check this article here - asp.net gridview example.

Saturday, May 6, 2017

Preventing Phantom Reads in SQL Server using Locks

preventing phanton reads in SQL Server using locks

In multi user systems, when a user is allowed to read data from a row that has been modified by another user and not yet committed, is known as Phantom Reads.

For example – I have a Students table that contains Students record. I update the student name, with id 5, from ‘Mila’ to ‘Maria’. But before it is committed, another user reads the student with id 5. The other user will get ‘Mila’ for the name but actually the ‘Mila’ is changed to ‘Maria’ and so it becomes Phantom Read (i.e. a non-existent record or phantom).

employee with id 5 in employee table

How to Prevent Phantom Reads

During the time of insert, update or delete work on the table, the SQL Server will automatically place the table under lock. So it will automatically prevent Phantom Reads.

But if one user removes the lock (for faster execution of query) then Phantom reads can happen

Note - Removing the lock can be done with this statement - with(nolock)

Suppose there are 2 users and both of them executes some SQL Statement.

Note - The second user executes the statement after 1 second.

First User executes:
begin tran
update Student set name='Maria' where ID=5
waitfor delay '00:00:15'
rollback     

Second User executes (after 1 second):

select name from Student with(nolock) where ID=5 

Here you can see that the first user changes the student name from ‘Mila’ to ‘Maria’ then after a delay of 15 seconds rolls back it to ‘Mila’.

The second, who executes the SQL statement by relaxing the lock will read the name as ‘Maria’. 

second user reads maria for student with id 5












The name ‘Maria’ is a Phantom (non-existant) since first user has reverted back to ‘Mila’

Note – The relaxation of lock can be used for faster execution of Queries in some situations. But I would not recommend using them when doing CRUD Operations in SQL Server.

You can run both the users statements in separate query window to see the result they give to you.

If the second user does not use with(nolock) then SQL Server will make him wait for 15 seconds till the lock gets removed and then gives him ‘Mila’ for the student with id 5.


Sunday, April 30, 2017

How to use jQuery AJAX with Entity Framework in ASP.NET MVC

jquery ajax

Introduction

This tutorial will help you to implement jQuery AJAX in your ASP.NET MVC project. You will also learn how to use Entity Framework in doing database operations. This tutorial is for Beginners and Intermediate coders who want to learn jQuery AJAX and Entity Framework.

The tutorial covers the following things –
  1. How to use jQuery AJAX in ASP.NET MVC. 
  2. How to use Entity Framework for doing DB operations. 
  3. How to apply jQuery Validations in the View. How to apply CSS in the view.

Requirements

I have used ASP.NET MVC 5.0 and Entity Framework 6.0 in this tutorial. However the codes will run on all MVC and EF versions.
  • The Database is SQL Server 2012. 
  • Visual Studio 2015 is used.

Project Briefings

In this project I will make a Database table in SQL Server. Then I will create a MVC form, on submitting this form, the form’s data will be sent to a function, defined on the Controller, using jQuery AJAX. This function will perform the insert in the DB table using Entity Framework and return the outcome of the operation.

STEP 1 – Creating the Database Table.

Let us first create a database table containing the student’s information. It will have the following fields.

Name
Type
Attribute
Id
INT
Identity Primary Key
Name
VARCHAR(50)
Not Null
Address
VARCHAR(50)
Not Null
Age
INT
Not Null
Standard
VARCHAR(10)
Not Null
Percent
DECIMAL(5,2)
Not Null
AddedOn
DATETIME
Not Null Default Binding getdate()
Status
BIT
Not Null

Database Table

database table

You can run the below Script in your database to generate the Student’s table:
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO
 
SET ANSI_PADDING ON
GO
 
CREATE TABLE [dbo].[Student](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Name] [varchar](50) NOT NULL,
    [Address] [varchar](100) NULL,
    [Age] [int] NOT NULL,
    [Standard] [varchar](10) NOT NULL,
    [Percent] [decimal](5, 2) NOT NULL,
    [AddedOn] [datetime] NOT NULL,
    [Status] [bit] NOT NULL,
 CONSTRAINT [PK_Student] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, 
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
 
GO
 
SET ANSI_PADDING OFF
GO
 
ALTER TABLE [dbo].[Student] ADD  CONSTRAINT [DF_Student_AddedOn]  DEFAULT (getdate()) 
FOR [AddedOn]
GO

There will also be an Insert Stored Procedure “sp_InsertStudent” which will insert entries in the student’s table. Note that this SP will be executed with the Entity Framework. The SP code is given below:
CREATE PROCEDURE [dbo].[sp_InsertStudent]   
    @Name        VARCHAR(50), 
    @Address     VARCHAR(100),   
    @Age         INT,
    @Standard    VARCHAR(10),
    @Percent     DECIMAL(5,2),
    @Status      BIT, 
    @Result      VARCHAR(50) OUTPUT,
    @CreatedId   INT OUTPUT     
AS           
BEGIN
    INSERT INTO Student(Name,Address,Age,Standard,[Percent],Status) VALUES 
    (@Name,@Address,@Age,@Standard,@Percent,@Status) 
    SET @Result='Insert Successful'   
    SET @CreatedId=@@IDENTITY
END

STEP 2 – Creating the Entity Data Model (EDM)

Now let’s move towards the Entity Framework. I will create EDM model of the Database, this EDM will create an .edmx file.

The EDMX file contains the knowledge of the database table, and the insert stored procedure.

Because of this EDMX file, we will be able to execute the “sp_GetStudent” SP from the MVC code.

Follow the Below Steps to create EDM:

a. Install “Entity Framework” from NuGet Package – Ignore this step if EF is already installed in your Project.

In the Visual Studio right click the project then select “Manage NuGet Packages” . Next, in the search box, enter “Entity FrameworK” and click enter.

Select the “Entity Framework” and click “Install” button.

b. Add “ADO.NET Entity Data Model” – In the Visual Studio right click the project. Then select “Add > New Item” – this will open “Add New Item” Window.

Next select “Visual C#” from the left side (under “Installed”), then select “ADO.NET Entity Data
Model” and click the “Add” button.

ADO.NET Entity Data Model

c. Choose Model Contents – Select “EF Designer from database” and click next button.

Choose Model Contents

d. Choose Your Data Connection – Click the “New Connection” button to open the “Connection Properties” window.

Enter the “Server name” and then select the database from “Select or enter a database name”.

Next click the “OK” button.

The “Connection Properties” window will close.

Click the “Next >” button.

Note – Select the database where you have created the “Student” table. Click the “Test Connection” button to find out whether the connection is alright or not.

Choose Your Data Connection

e. Choose Your Database Objects and Settings – Check the “Tables” and “Stored Procedures and Functions”. This is because I have one table and one stored procedure and I want the EDM to have the knowledge of both of them.

Finally click the “Finish” button. Choose Your Database Objects and Settings

Finally our EDMX file will be created and it will have the students table shown over it. edmx file

STEP 3 – Creating the Controller

Right click the “Controller” folder in your project and select “Add > Controller”. Next Click “MVC 5 Controller – Empty” and click “Add” button.

Give the Controller name as “InsertController” and click the “Add” button.

creating the controller

The controller will open in the Visual Studio. Now start entering the code.

First add the entity namespace to the controller -


using System.Data.Entity.Core.Objects;

Then create an insert function in the controller. This function will call the “InsertStudent” stored procedure. Notice how I have defined the 2 output parameter of the SP as type “ObjectParameter”.
This function - I will call through the jQuery AJAX method from the view. I will explain how to do this in STEP 7.

The values of the “result” output parameter is returned at the last line.

[HttpPost]
public string Insert(string name, string age, string standard, string percent, 
    string address, string status)
{
    using (var context = new Entities())
    {
        ObjectParameter result = new ObjectParameter("result", typeof(String));
        ObjectParameter createdId = new ObjectParameter("createdId", typeof(String));
        context.sp_InsertStudent(name, address, Convert.ToInt32(age), standard,
            Convert.ToDecimal(percent), Convert.ToBoolean(Convert.ToInt32(status)), result, createdId);
        return result.Value.ToString();
    }
}

STEP 4 – Creating the View

In your project open the “Views” folder where you will see the “Insert” folder. Right click the “Insert” folder and select “Add > View”. Give the view name as “Index” and click the “Add” button.

This will create the view.

Creating the View


STEP 5 – Creating the Student Form in the View

Now I will create the “Student” form with all the fields given in the “Student” table. I will not include the “Id” and “AddedOn” as they are auto-generated fields.

The below code will create the student form in the “Index” view:
<div id="messageDiv"></div>
<div class="studentFormDiv">
    @using (Html.BeginForm())
    {
        <table>
            <tr>
                <td>
                    <label>name</label>
                    <input id="name" type="text">
                    <span class="nameSpan"></span>
                </td>
                <td>
                    <label>age</label>
                    <input id="age" name="age" type="number">
                    <span class="ageSpan"></span>
                </td>
            </tr>
            <tr>
                <td>
                    <label>standard</label>
                    <input id="standard" type="text">
                    <span class="standardSpan"></span>
                </td>
                <td>
                    <label>percent</label>
                    <input id="percent" type="text">
                    <span class="percentSpan"></span>
                </td>
            </tr>
            <tr>
                <td>
                    <label>address</label>
                    <input id="address" type="text">
                    <span class="addressSpan"></span>
                </td>
                <td>
                    <label>status</label>
                    <select id="status">
                        <option value="Select">Select</option>
                        <option value="1">Active</option>
                        <option value="0">InActive</option>
                    </select>
                    <span class="statusSpan"></span>
                </td>
            </tr>
            <tr><td><button id="submitButton" type="submit">Submit</button></td></tr>
        </table>
    }
</div>

Explanation – The above form will be filled and submitted on clicking the submit button at the bottom. On clicking the button the jQuery AJAX will call the C# function “Insert”. The returned value from the C# function will be shown in the “messageDiv” div.

STEP 6– Applying the Styles to the Form

To give the little bit of styling to this form add the CSS to the view, on top of the form:
<style>
    .studentFormDiv label {
        display: block;
        margin: 0;
        text-transform: capitalize;
    }
    .studentFormDiv span {
        display: block;
        color: red;
    }
    .studentFormDiv > form > div > div {
        padding-top: 25px;
    }
    table {
        width: 100%;
    }
    h1 {
        border-bottom: solid 3px #CCC;
    }
</style>

STEP 7 – Using jQuery AJAX to Call the Insert Function

On the ”submitButton” button click event I will validate all the form’s fields with jQuery. When all the field values are correct then I will use jQuery AJAX method to call the C# function named “insert”. The student’s field values will be sent to this function as parameters. Since this function will be called using jQuery AJAX so there will be no page postback.

form

title

The jQuery Code is given below:
<script>
    $(document).ready(function () {
        $("#submitButton").click(function (e) {
            var returnValidate = Validate();
            if (returnValidate) {
                $.ajax({
                    type: "POST",
                    url: "/insert/insert",
                    contentType: "application/json; charset=utf-8",
                    data: '{"name":"' + $("#name").val() + '","age":"' + $("#age").val()
+ '","standard":"' + $("#standard").val() + '",
"percent":"' + $("#percent").val() + '","address":"'
+ $("#address").val() + '","status":"' + $("#status").val()
+ '"}',
                    dataType: "html",
                    success: function (result, status, xhr) {
                        $("#messageDiv").html(result);
                    },
                    error: function (xhr, status, error) {
                        $("#messageDiv").html(status);
                    }
                });
            }
            return false;
        });
        function Validate() {
            var errorCounter = 0;
            $(".nameSpan").text("");
            $(".ageSpan").text("");
            $(".standardSpan").text("");
            $(".percentSpan").text("");
            $(".statusSpan").text("");
            if ($("#name").val() == "") {
                $(".nameSpan").text("Please enter name");
                errorCounter++;
            }
            if ($("#age").val() == "") {
                $(".ageSpan").text("Please enter age");
                errorCounter++;
            }
            else if (!(isPositiveInteger($("#age").val()))) {
                $(".ageSpan").text("Age should be in +ve integers");
                errorCounter++;
            }
            if ($("#standard").val() == "") {
                $(".standardSpan").text("Please enter standard");
                errorCounter++;
            }
            if ($("#percent").val() == "") {
                $(".percentSpan").text("Please enter percent");
                errorCounter++;
            }
            else if (!(isPercent($("#percent").val()))) {
                $(".percentSpan").text("Percent should be integers or decimal");
                errorCounter++;
            }
            if ($("#status").val() == "Select") {
                $(".statusSpan").text("Please select status");
                errorCounter++;
            }
            if (errorCounter == 0) {
                return true;
            }
            else {
                return false;
            }
        }
        function isPositiveInteger(n) {
            return ($.isNumeric(n) && (n > 0));
        }
        function isPercent(n) {
            return (n.match(/(^100(\.0{1,2})?$)|(^([1-9]([0-9])?|0)(\.[0-9]{1,2})?$)/));
        }
    });
</script>

I passed “/index/insert” to the jQuery AJAX function to call the “insert” function of the “insert” controller. The C# function’s returned value is shown by the “success: function(){}” given inside the jQuery AJAX method.

STEP 8 – Configuring RouteConfig.cs

To set “Index” view of the “Insert” controller as the starting page of our project, update the RouteConfig.cs file (inside the App_Start folder) as shown below-

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Insert", action = "Index", id = UrlParameter.Optional }
);

Testing

To test it, let us fill and submit the form. You will see the jQuery AJAX will call the C# function, which in turn will insert the values and return a message. This return message will be shown in the div.

Summary

This tutorial will help you to learn Entity Framework & jQuery AJAX in ASP.NET MVC. From this tutorial you can go on and learn more about the different Entity Framework topics.
Please mark and vote for this tutorial and give me your suggestions.
Also share this article with your friends on email, Facebook, Twitter & Google Plus.
I hope you liked this tutorial!

How to use SyntaxHighlighter in your website

SyntaxHighlighter is a JavaScript code that highlights programming languages codes in different colors and fonts. This helps to understan...