In this article, I will show you how to build a JQuery/AJAX enabled ASP.NET MVC application.
In this demo example, I have a web page with a button and once user click the button, data is retrieved from SQL Server database using JQuery/AJAX calls and displayed on a table.
Steps
1. Create new MVC Web Application.
Project Name: MvcAjaxTutorial
2. This is how the folder structure looks on newly created project.
3. Now we need to work on our database.
I have a table called "Product" in my SQL Server database.
Database Name: NHibernateWeb
Table Name: Product
Table create SQL:
CREATE TABLE [dbo].[Products]
(
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](50) NULL,
[Description] [nvarchar](max) NULL,
[Price] [decimal](18, 0) NULL,
[UnitsInStock] [int] NULL,
CONSTRAINT [PK_Products] 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]
Insert data SQL:
INSERT INTO [Products]
([Name],[Description],[Price],[UnitsInStock])
VALUES
('Nescafe', 'Milk Powder', 75, 25)
INSERT INTO [Products]
([Name],[Description],[Price],[UnitsInStock])
VALUES
('Coke', 'Soft Drink', 25, 75)
4. Make sure you add "System.Data.Linq" reference to the project.
This can be done by right click on "Reference" and by adding the reference.
5. Now we need to create our Model.
Inside the "Model" folder create a class called "Product.cs"
Add bellow code to "Product.cs" file.
[Table(Name = "Products")]
public class Product
{
[Column(IsPrimaryKey = true)]
public int Id { get; set; }
[Column]
public string Name { get; set; }
[Column]
public string Description { get; set; }
[Column]
public decimal Price { get; set; }
[Column]
public int UnitsInStock { get; set; }
}
6. You can see there are some underlined syntax error.
To overcome those error, we need to add:
using System.Data.Linq;
using System.Data.Linq.Mapping;
7. Next create a new folder called "Context" and inside that create new a class called "ProductsContext.cs"
In that class we will be defining our connection string to SQL Server Database. Add bellow code in there.
public class Connections
{
public static string connection = "Data Source=localhost;Initial Catalog=NHibernateWeb;user id=sa;password=sa123;";
}
8. Next we add bellow piece of code to "HomeController.cs"
DataContext context;
public HomeController()
{
this.context = new DataContext(Connections.connection);
}
public ViewResult GetProducts()
{
Product[] products = context.GetTable<Product>().ToArray();
return View(products);
}
9. You can see there are some underlined syntax error.
To overcome those error, we need to add:
using MvcAjaxTutorial.Context;
using MvcAjaxTutorial.Models;
using System.Data.Linq;
10. Generate a new view on the newly created ViewResult - GetProducts()
Right click on "GetProducts()" and the menu select "Add View".
11. Add following piece of code to that newly created view.
@using MvcAjaxTutorial.Models
@{
ViewBag.Title = "Products";
}
<div>
<input id="btnGetProducts" name="btnGetProducts" type="button" value="Get Products" />
<br />
<br />
<div id="products"></div>
</div>
@section Scripts {
<script>
$('#btnGetProducts').click(function ajaxCall() {
$.ajax({
url: '/Home/GetProducts',
contentType: 'application/html; charset=utf-8',
type: 'GET',
dataType: 'html'
})
.success(function (result) {
$('#products').html(result);
})
.error(function (xhr, status) {
alert(status);
})
}
);
</script>
}
12. All ready setup I guessed. Run the project.
All the Project Code
Bellow is a all the list of code pieces that is used in this tutorial.
HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcAjaxTutorial.Context;
using MvcAjaxTutorial.Models;
using System.Data.Linq;
namespace MvcAjaxTutorial.Controllers
{
public class HomeController : Controller
{
DataContext context;
public HomeController()
{
this.context = new DataContext(Connections.connection);
}
public ViewResult GetProducts()
{
Product[] products = context.GetTable<Product>().ToArray();
return View(products);
}
public ActionResult Index()
{
Product[] products = context.GetTable<Product>().ToArray();
return View(products);
}
public ActionResult About()
{
ViewBag.Message = "Your app description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
}
Product.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Linq;
using System.Data.Linq.Mapping;
namespace MvcAjaxTutorial.Models
{
[Table(Name = "Products")]
public class Product
{
[Column(IsPrimaryKey = true)]
public int Id { get; set; }
[Column]
public string Name { get; set; }
[Column]
public string Description { get; set; }
[Column]
public decimal Price { get; set; }
[Column]
public int UnitsInStock { get; set; }
}
}
ProductContext.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcAjaxTutorial.Context
{
public class ProductsContext
{
}
public class Connections
{
public static string connection = "Data Source=localhost;Initial Catalog=NHibernateWeb;user id=sa;password=sa123;";
}
}
GetProducts.cshtml
@using MvcAjaxTutorial.Models
@model IEnumerable<Product>
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Description</th>
<th>Price</th>
<th>UnitsInStocks</th>
</tr>
@foreach (Product p in Model)
{
<tr>
<td>@p.Id</td>
<td>@p.Name</td>
<td>@p.Description</td>
<td>@p.Price</td>
<td>@p.UnitsInStock</td>
</tr>
}
</table>
Index.cshtml
@using MvcAjaxTutorial.Models
@{
ViewBag.Title = "Products";
}
<div>
<input id="btnGetProducts" name="btnGetProducts" type="button" value="Get Products" />
<br />
<br />
<div id="products"></div>
</div>
@section Scripts {
<script>
$('#btnGetProducts').click(function ajaxCall() {
$.ajax({
url: '/Home/GetProducts',
contentType: 'application/html; charset=utf-8',
type: 'GET',
dataType: 'html'
})
.success(function (result) {
$('#products').html(result);
})
.error(function (xhr, status) {
alert(status);
})
}
);
</script>
}
That's it!.Enjoy!
Add a comment