ASP.NET MVC 4 Tutorial :: Creating Google Column Chart With Animation

In this tutorial, we will discuss about creating Google column chart with animation on load using ASP.NET MVC4 & Jquery. A column chart is a vertical bar chart rendered in the browser using SVG or VML, whichever is appropriate for the user’s browser. Like all Google charts, column charts display tooltips when the user hovers over the data. For a horizontal version of this chart, see the bar chart.

Steps :

1 – Create New Project.

Go to File > New > Project > Select asp.net MVC4 web application > Entry Application Name > Click OK > Select Internet Application > Select view engine Razor > OK

2 – Add a Database.

Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add.

3 – Create table for get data for chart.

Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > Ok.

In this example, I have used one tables as below

4- Add Entity Data Model.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.
A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >
Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish.

5 – Add a new Controller.

Go to Solution Explorer > Right Click on Controllers folder form Solution Explorer > Add > Controller > Enter Controller name > Select Templete “empty MVC Controller”> Add.

6 -Add new action into your controller for Get Method.

Here I have added “Column” Action into “GoogleChart” Controller. Please write this following code

public ActionResult Column()

{

return View();

}

7 – Add view for the Action & design.

Right Click on Action Method (here right click on form action) > Add View… > Enter View Name > Select View Engine (Razor) > Check “Create a strong-typed view” > Select your model class > Add.

8 – Add jquery code for create google animated Chart.

<script>

$(document).ready(function () {

//Load Data Here

var chartData = null;

$.ajax({

url: '/GoogleChart/GetSalesData',

type: 'GET',

dataType: 'json',

data: '',

success: function (d) {

chartData = d;

},

error: function () {

alert('Error!');

}

}).done(function () {

drawChart(chartData);

});

});

 

function drawChart(d) {

var chartData = d;

var data = null;

data = google.visualization.arrayToDataTable(chartData);

 

var view = new google.visualization.DataView(data);

view.setColumns([0, {

type: 'number',

label: data.getColumnLabel(0),

calc: function () { return 0; }

}, {

type: 'number',

label: data.getColumnLabel(1),

calc: function () { return 0; }

}, {

type: 'number',

label: data.getColumnLabel(2),

calc: function () { return 0; }

}, {

type: 'number',

label: data.getColumnLabel(3),

calc: function () { return 0; }

}]);

 

var chart = new google.visualization.ColumnChart(document.getElementById('visualization'));

var options = {

title: 'Sales Report',

legend: 'bottom',

hAxis: {

title: 'Year',

format: '#'

},

vAxis: {

minValue: 0,

maxValue: 1000000,

title: 'Sales Amount'

},

chartArea: {

left:100, top: 50, width:'70%', height: '50%'

},

animation: {

duration: 1000

}

};

 

var runFirstTime = google.visualization.events.addListener(chart, 'ready', function () {

google.visualization.events.removeListener(runFirstTime);

chart.draw(data, options);

});

 

chart.draw(view, options);

}

google.load('visualization', '1', { packages: ['corechart'] });

</script>

 

9 – Add another new action into your controller for fetch json data for Chart.

Here I have added “GetSalesData” Action into “GoogleChart” Controller. Please write this following code

public JsonResult GetSalesData()

{

List<SalesData> sd = new List<SalesData>();

using (MyDatabaseEntities dc = new MyDatabaseEntities())

{

sd = dc.SalesDatas.OrderBy(a => a.Year).ToList();

}

 

var chartData = new object[sd.Count + 1];

chartData[0] = new object[]{

"Year",

"Electronics",

"Book And Media",

"Home And Kitchen"

};

int j = 0;

foreach (var i in sd)

{

j++;

chartData[j] = new object[] {i.Year, i.Electronics, i.BookAndMedia, i.HomeAndKitchen };

}

 

return new JsonResult {Data = chartData, JsonRequestBehavior = JsonRequestBehavior.AllowGet };

}

 

Complete View

@{

ViewBag.Title = "Column";

}

 

<h2>Column Chart With Animation</h2>

 

<br />

<div id="visualization" style="width:600px; height:300px">

 

</div>

 

<script type="text/javascript" src="https://www.google.com/jsapi"></script>

@section Scripts{

<script>

$(document).ready(function () {

//Load Data Here

var chartData = null;

$.ajax({

url: '/GoogleChart/GetSalesData',

type: 'GET',

dataType: 'json',

data: '',

success: function (d) {

chartData = d;

},

error: function () {

alert('Error!');

}

}).done(function () {

drawChart(chartData);

});

});

 

function drawChart(d) {

var chartData = d;

var data = null;

data = google.visualization.arrayToDataTable(chartData);

 

var view = new google.visualization.DataView(data);

view.setColumns([0, {

type: 'number',

label: data.getColumnLabel(0),

calc: function () { return 0; }

}, {

type: 'number',

label: data.getColumnLabel(1),

calc: function () { return 0; }

}, {

type: 'number',

label: data.getColumnLabel(2),

calc: function () { return 0; }

}, {

type: 'number',

label: data.getColumnLabel(3),

calc: function () { return 0; }

}]);

 

var chart = new google.visualization.ColumnChart(document.getElementById('visualization'));

var options = {

title: 'Sales Report',

legend: 'bottom',

hAxis: {

title: 'Year',

format: '#'

},

vAxis: {

minValue: 0,

maxValue: 1000000,

title: 'Sales Amount'

},

chartArea: {

left:100, top: 50, width:'70%', height: '50%'

},

animation: {

duration: 1000

}

};

 

var runFirstTime = google.visualization.events.addListener(chart, 'ready', function () {

google.visualization.events.removeListener(runFirstTime);

chart.draw(data, options);

});

 

chart.draw(view, options);

}

google.load('visualization', '1', { packages: ['corechart'] });

</script>

}

10 – Run Application.

 

ASP.NET MVC 6 Tutorial :: How to Search Record in MVC With Ajax and jQuery?

Today’s turotial is about how to search record in MVC with Ajax and jQuery. This code will filter out all matching records group by table column name.
hflnet52

First thing that you should do is create an empty ASP.NET MVC project. Now, add two class to your model. Employee and DemoContext and write the following code:

namespace SearchingDemo.Models
{
public class Employee
{
[Key]
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Position { get; set; }
}
}
namespace SearchingDemo.Models
{
public class DemoContext : DbContext
{
public DbSet<Employee> Employees { get; set; }
}
}

Add a Home Controller. Now, Add index Action to controller. and create corresponding view.

public ActionResult Index()
{
return View();
}

Now, write the following code to Index View.
<link href="~/Content/Style.css" rel="stylesheet" />
<script src="~/Content/jquery-2.1.1.min.js"></script>
<script src="~/Content/CustomJs.js"></script>
<h2>Seaching Demo</h2>
<div class="divFind">
<table>
<tr>
<td>
<input type="text" id="txtSearch" />
</td>
<td>
<input type="button" id="btnSearch" value="Seach" />
</td>
</tr>
</table>
</div>
<div id="divList">
</div>

Write the .JS code for click event on seach button to get filtered result. add following .JS code.

$(document).ready(function () {
$('#btnSearch').on('click', function () {
var getkey = $('#txtSearch').val();
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: 'Home/Search',
data: "{ 'searchKey':' " + getkey + "' }",
success: function (data) {
BindData(data);
},
error: function (data) {
alert('Error in getting result');
}
});
});
});
function BindData(data) {
var ulList = '<ul>';
var resultType = ["FirstName", "LastName", "Position"];
$.each(data, function (i, d) {
ulList += '<li class="SeachType">' + resultType[i] + '</li>';
if (d.length > 0) {
$.each(d, function (key, value) {
ulList += '<li>' + value.FirstName + ' - ' + value.LastName + ' - ' + value.Position + '</li>'
});
} else {
ulList += '<li><span class="red">No Results</span></li>';
}
});
ulList += '</ul>'
$('#divList').html(ulList);
}

Javascript code calling search function, which is written in controller. Add search function to your controller.

public JsonResult Search(string searchKey)
{
DemoContext dbObj = new DemoContext();
var getKey = searchKey.Trim();
var getFirstName = dbObj.Employees.Where(n => n.FirstName.Contains(getKey)).ToList();
var getLastName = dbObj.Employees.Where(n => n.LastName.Contains(getKey)).ToList();
var getPostion = dbObj.Employees.Where(n => n.Position.Contains(getKey)).ToList();
IList<IList<Employee>> getTotal = new List<IList<Employee>>();
getTotal.Add(getFirstName);
getTotal.Add(getLastName);
getTotal.Add(getPostion);
int count = getTotal.Count();
return Json(getTotal);
}

 

HostForLIFE.eu ASP.NET MVC 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.