Showing posts with label ASP.Net MVC. Show all posts
Showing posts with label ASP.Net MVC. Show all posts

Sunday, 31 December 2017

Convert ASP.NET MVC dropdownlist into multi select textbox using Chosen JS plugin

In this article, I am going to explain you how to convert asp.net mvc dropdownlist into multi select textbox using Chosen JS plugin. You can see in below figure how the dropdown will look like after converting into multi select textbox.

Convert ASP.NET MVC dropdownlist into multi select textbox using Chosen JS plugin

Creating ASP.NET MVC Empty Application

Now the next step is to create ASP.NET MVC empty application as shown below.
Go to FileNewProject. A new window will be open as shown below.
Now go to Web and select .NET Framework 4.5 and give project name and click on OK .

Creating asp.net mvc 5 application

Now new window will open as shown below.
Now Select Empty Template, check on MVC checkbox and click on OK.

Selecting asp.net mvc 5 empty template

Now, a new project will be created as shown below.

Asp.net mvc 5 empty folder structure

Adding Models

Go to Models folder and add new class file CountryData.cs. Now replace all code with below code. Here we have one list property CountryList which is type of SelectListItem for holding list of country data. Four string property for holding Id of 4 different dropdowns which we will see in article.

Share:

Friday, 22 December 2017

DatePicker or Calendar Control in ASP.NET MVC using jQuery UI

In this tutorial, I am going to explain you how to attach DatePicker or Calendar control in ASP.NET MVC using jQuery UI. I will be using Visual Studio 2013. Below is step by step tutorial.

Creating ASP.NET MVC Empty Application

Now the next step is to create ASP.NET MVC empty application as shown below.
Go to FileNewProject. A new window will be open as shown below.
Now go to Web and select .NET Framework 4.5 and give project name and click on OK .

Creating asp.net mvc 5 application

Now new window will open as shown below.
Now Select Empty Template, check on MVC checkbox and click on OK.

Selecting asp.net mvc 5 empty template

Now, a new project will be created as shown below.

Asp.net mvc 5 empty folder structure

Installing jQuery UI using Nuget (Compulsory)

Next step is to install jQuery.UI. Right click on References and go to Manage NuGet Packages as shown below.

Manage NuGet Packages in ASP.NET MVC

After that a new window will open as shown below. Search for jQuery.UI and install it.

Installing jQuery.UI in ASP.Net Mvc

After successful installation, you can see all css files related to datepicker are installed inside Content folder and and jquery-ui file is installed inside Scripts folder.

After successfull installation of jQuery.UI in ASP.Net Mvc

Installing Bootstrap and Unobtrusive jQuery (Optional)

If bootstrap js,css and Unobtrusive jQuery is not install in your application then you can install using nuget package manager.
Bootstrap: It is used for CSS and responsive design.
Unobtrusive jQuery: It is to make data annotation work at client machine.

Installing Bootstrap and Unobtrusive jQuery in ASP.Net Mvc

Adding Models

Go to Models folder and add new class file Employee.cs. Now replace all code with below code.

Share:

Sunday, 10 December 2017

Grid.MVC with MultiSelect DropDownList with CheckBox auto selected from database in MVC

In this tutorial, I am going to explain you bind how to bind multiple selection (MultiSelect) DropDownList with CheckBox in Grid.MVC in ASP.Net MVC from database using jQuery, Bootstrap and MultiSelect JS. I will be using Visual Studio 2013 and ADO.Net code to get data from SQL-Server Database.

As you can see in below screen-shot, multi-select dropdownlist is auto-selected. Here in Subject column , subject value is concatenated with comma from database, while binding to MVCGrid subject is auto selected in last column as shown below.

Grid.MVC with MultiSelect DropDownList with CheckBox auto selected from database in MVC

Creating Table and Procedure

Use below script to create a Student Table and procedure to fetch data from database.

Share:

Friday, 10 November 2017

Implement Chart using DotNet HighCharts in ASP.NET MVC

In this article, I am going to explain you how to implement chart using DotNet HighCharts in ASP.NET MVC. Here we will create chart using hard-coded value but in later articles I will explain draw chart from database. Below is step by step tutorial.

Creating ASP.NET MVC Empty Application

Now the next step is to create ASP.NET MVC empty application as shown below.
Go to FileNewProject. A new window will be open as shown below.
Now go to Web and select .NET Framework 4.5 and give project name and click on OK .

Creating asp.net mvc 5 application

Now new window will open as shown below.
Now Select Empty Template, check on MVC checkbox and click on OK.

Selecting asp.net mvc 5 empty template

Now, a new project will be created as shown below.

Asp.net mvc 5 empty folder structure

Installing DotNet.HighCharts

Now the next step is DotNet.HighCharts. Go to TOOLS → Library Package Manager → Manage NuGet Packages for Solution.. and a new window will open. Type and search for DotNet.HighChart and click on Install button as shown below. Once installed successfully, you can check DotNet.HighChart in references folder.

Adding DotNet.HighCharts
Installing DotNet.HighCharts

You can also install by using Package Manager Console. Go to TOOLS → Library Package Manager → Package Manager Console → write Install-Package DotNet.HighCharts and press enter. This will install DotNet.HighCharts in application.

Adding Controller

Next step is to add Controller to application. Add a new empty Controller class named as HomeController. After adding controller, a new action method will be created. Replace all code with below code.

Share:

Saturday, 21 October 2017

MVC MultiSelect (Multiple Selection) DropdownList with CheckBoxes Using jQuery

In this tutorial, I am going to explain you how to implement multiple selection (MultiSelect) DropDownList with CheckBox in MVC using jQuery, Bootstrap and MultiSelect JS.

Creating MVC Model

First of all, we need to create model. Write click on Models folder and add a new class name as CountryModel. Replace all code with below code. CountryList property is used to store List of Country and SelCountry property is used to store selected country while passing to the controller.

Share:

Saturday, 14 October 2017

Bind menu and sub-menu dynamically in mvc from database

In this article, I am going to explain you binding menu and sub-menu dynamically from database in asp.net mvc with razor view engine. I will be using visual studio 2013 edition and sql server 2008. Below is the step by step tutorial.

Creating Database Table

We will be using 4 following tables.
RoleMaster
UserMaster
MenuMaster
RoleMenuMapping

RoleMaster and UserMaster
RoleMaster and UserMaster Table
MenuMaster
MenuMaster Table
RoleMenuMapping
RoleMenuMapping Table

Below is the script to create all the tables and insert some data into it.

Share:

Saturday, 16 September 2017

Delete multiple record from WebGrid in ASP.NET MVC using CheckBox

In this article, I am going to explain you how to delete multiple records from ASP.NET MVC WebGrid with the help of CheckBox and Delete button. In this tutorial, we will be discussing only deleting the records. Insert and update will discuss in later tutorials.

I am using visual studio 2013 ultimate, SQL-Server database and Dapper Micro ORM to map database tables to model entity. Below is step by step tutorial.

Creating Database Table

Below is script to create database table and insert some dummy records.

CREATE TABLE tbl_Employee
(
EmpID INT PRIMARY KEY IDENTITY,
Name VARCHAR(100),
Salary INT,
City VARCHAR(50),
Country VARCHAR(50)
)
GO
INSERT INTO tbl_Employee VALUES('Rahul',10000,'Mumbai','India')
INSERT INTO tbl_Employee VALUES('Deepak',15200,'Mumbai','India')
INSERT INTO tbl_Employee VALUES('Savio',15000,'Delhi','India')
INSERT INTO tbl_Employee VALUES('Yogesh',10500,'Mumbai','India')
INSERT INTO tbl_Employee VALUES('Sachin',17000,'Chennai','India')
INSERT INTO tbl_Employee VALUES('Ponting',80000,'Sydney','Australia')
INSERT INTO tbl_Employee VALUES('Josh',24463,'Perth','Australia')
INSERT INTO tbl_Employee VALUES('Johnson',24562,'Melbourne','Australia')
INSERT INTO tbl_Employee VALUES('Gimmy',32456,'Perth','Australia')
INSERT INTO tbl_Employee VALUES('Rex',68355,'Sydney','Australia')
INSERT INTO tbl_Employee VALUES('Rick',99999,'New York','USA')
INSERT INTO tbl_Employee VALUES('Savy',15465,'Chicago','USA')
INSERT INTO tbl_Employee VALUES('Todd',24562,'New York','USA')
INSERT INTO tbl_Employee VALUES('Mary',35485,'New York','USA')
INSERT INTO tbl_Employee VALUES('Mike',15245,'Chicago','USA')

Creating ASP.NET MVC Project

Next step is to create asp.net mvc project.
Go to FileNewProject. A new window will be open as shown below.
Now go to Web and select .NET Framework 4.5 and give project name and click on OK .

Creating asp.net mvc 5 application

Now new window will open as shown below.
Now Select Empty Template, check on MVC checkbox and click on OK.

Selecting asp.net mvc 5 empty template

Now, a new project will be created as shown below.

Asp.net mvc 5 folder structure

Installing Dapper Micro-ORM

Next step is to install Dapper Micro-ORM. Right click on References and go to Manage NuGet Packages as shown below.

Adding Dapper ORM using NuGet Packages

After that a new window will open as shown below. Search for Dapper ORM and install it.

Installing dapper orm

Creating Model

Now add a class file Employee.cs in Models folder. Add below properties to Employee class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
 
namespace WebGridDemo.Models
{
    public class Employee
    {
        public int EmpID { get; set; }
        public string Name { get; set; }
        public int Salary { get; set; }
        public string City { get; set; }
        public string Country { get; set; }
    }
}

Now add a New Folder and rename as Repository to root directory of application. Add a class file EmployeeMaster.cs inside Repository folder. Create two methods GetAllEmployees and DeleteRecords inside EmployeeMaster class. GetAllEmployees method executes stored a procedure which returns IEnumerable of type Employee. DeleteRecords method uses in-line query to delete record by using EmpID.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Dapper;// add namespance
using WebGridDemo.Models;// add namespance
using System.Data.SqlClient;// add namespance
using System.Configuration;// add namespance
using System.Data; // add namespance

namespace WebGridDemo.Repository
{
  public class EmployeeMaster
  {
    public IEnumerable<Employee> GetAllEmployees()
    {
       //using stored procedure to fetch all the records
       using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBCS"].ToString()))
       {
         try
         {
             var emp_list = con.Query<Employee>("usp_GetEmployeeDetails", null, null, true, 0, CommandType.StoredProcedure);
             return emp_list;
         }
         catch
         {
             return null;
         }
       }
    }
    public void DeleteRecords(int id)
    {
       //using inline sql query to delete records
       using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBCS"].ToString()))
       {
         try
         {
             string query = "delete from tbl_Employee where EmpID=@EmpID";
             var abc = con.Execute(query, new { EmpID = id });
         }
         catch
         {
             //return null;
         }
       }
    }
  }
}

Below is the script for stored procedure to fetch data.

CREATE proc usp_GetEmployeeDetails
AS
BEGIN
 SELECT * FROM tbl_Employee
END

Adding Controller

Next step is to add controller to application. Add a new empty controller class named as HomeController and add two action methods as shown below. Index method is used to return list of employee to the Index view and DeleteRecords is post method used to delete the records.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebGridDemo.Models;// add namespace
using WebGridDemo.Repository; // add namespace

namespace WebGridDemo.Controllers
{
    public class HomeController : Controller
    {
        [HttpGet]
        public ActionResult Index()
        {
            EmployeeMaster obj = new EmployeeMaster();
            List<Employee> emplist = new List<Employee>();
            emplist = obj.GetAllEmployees().ToList();
            return View(emplist);
        }

        [HttpPost]
        public ActionResult DeleteRecords(string[] EmpIDs)
        {
            if (EmpIDs != null && EmpIDs.Length > 0)
            {
                foreach (var id in EmpIDs)
                {
                    EmployeeMaster obj = new EmployeeMaster();
                    obj.DeleteRecords(Convert.ToInt32(id));
                }
            }
            return RedirectToAction("Index");
        }
    }
}

Adding View

Next step is to add view. Right click inside index action method and add a new view named as Index and select empty model and add a View. Now open Index.cshtml view which is created inside Views/Home folder. Replace all code with below code.

@model IEnumerable<WebGridDemo.Models.Employee>

@{
    ViewBag.Title = "WebGrid Demo";
    var grid = new WebGrid(canSort: true, rowsPerPage: 5);
    grid.Bind(source: Model);
}

<style>
    .header_style {
        background-color: #055897;
        color: #ffffff;
    }

        .header_style a {
            color: #ffffff !important;
        }

    .table-pager > td {
        padding-top: 10px;
    }

        .table-pager > td > a {
            background-color: #f5f5f5;
            border: 1px solid #ccc;
            border-radius: 3px;
            padding: 3px 7px;
        }

            .table-pager > td > a:hover {
                background-color: #f0f0f0;
            }

    .webgrid-alternating-row {
        background-color: #EAF2D3;
        padding: 3px 7px 2px;
    }
</style>

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/core.js" type="text/javascript"></script>

<h3 class="text-info">Delete Multiple Reords in WebGrid in MVC</h3>

<div class="test" style="overflow: scroll; width: auto;">
    <div style="width: auto">
        @using (Html.BeginForm("DeleteRecords", "Home", FormMethod.Post))
        {
            if (Model.Count() > 0)
            {
                @grid.GetHtml(
                tableStyle: "table table-responsive table-bordered",
                headerStyle: "header_style",
                rowStyle: "odd",
                alternatingRowStyle: "webgrid-alternating-row",
                footerStyle: "table-pager",
                firstText: "First",
                lastText: "Last",
                nextText: "Next",
                previousText: "Previous",
                columns: grid.Columns
                (
                grid.Column(format: @<text><input type="checkbox" name="EmpIDs" value="@item.EmpId" /></text>, header: "Select"),
                grid.Column("EmpId", "Employee ID"),
                grid.Column("Name", "Employee Name"),
                grid.Column("Salary", "Salary"),
                grid.Column("City", "City"),
                grid.Column("Country", "Country"),
                grid.Column(
                 "Action", format: (item) =>
                 {
                     var links =
                     Html.ActionLink("  ", "Edit", "Product", new { id = item.EmpID }, new { @class = "btn btn-default glyphicon glyphicon-edit" }).ToHtmlString() +
                     Html.ActionLink("  ", "Delete", "Product", new { }, new { @class = "btn btn-default glyphicon glyphicon-remove delete-product", @data_id = item.EmpID }).ToHtmlString();

                     return Html.Raw(links);
                 }
                 , canSort: false)
              ),
mode: WebGridPagerModes.All
)
                <input type="submit" class="btn btn-danger" value="Delete Selected Records" />
            }
            else
            {
             <p class="text-info, text-danger">No Records Found</p>
             <table class="table table-responsive table-bordered">
                 <thead>
                     <tr class="header_style">
                         <th scope="col">
                             Select
                         </th>
                         <th scope="col">
                             Employee ID
                         </th>
                         <th scope="col">
                             Name
                         </th>
                         <th scope="col">
                             Salary
                         </th>
                         <th scope="col">
                             City
                         </th>
                         <th scope="col">
                             Country
                         </th>
                     </tr>
                 </thead>
             </table>
            }
        }
    </div>
</div>

Right now the Edit and Delete buttons will not be working. We will discuss in later articles. Now run your application, you can see the records will be displayed in WebGrid. You can select record using checkbox and Click on "Delete Selected Records" to delete records.

Display and deleting record from webgrid
Share:

Saturday, 2 September 2017

Draw or implement Pie Chart, Column Chart and Doughnut Chart using Google Chart API in ASP.NET MVC

In this article, I am going to explain you how to draw or implement Pie Chart, Column Chart and Doughnut Chart using Google Chart API in ASP.NET MVC. We will first Entity Framework to load data from database and after that we will use ADO.NET code. Below is the step by step tutorial.

Creating Database Table

First we need to create a database table and insert some dummy records. Below is table script to create table. Table ProductSales has 3 columns Id, Month and SalesCount. Here we are plotting number of product sales against each month.
create table ProductSales
(
Id int primary key identity,
[Month] varchar(20),
SalesCount int
)
go
insert into ProductSales values('Jan',85)
insert into ProductSales values('Feb',90)
insert into ProductSales values('Mar',30)
insert into ProductSales values('Apr',46)
insert into ProductSales values('May',65)
insert into ProductSales values('Jun',75)
insert into ProductSales values('Jul',85)
insert into ProductSales values('Aug',60)
insert into ProductSales values('Sep',55)
insert into ProductSales values('Oct',40)
insert into ProductSales values('Nov',60)
insert into ProductSales values('Dec',90)

Adding Controller and Controller Action Method

The next step is to add controller and action method. Add a new controller named as HomeController and inside controller add a new action method ChartFunction as shown below. Return type of ChartFunction() should be JsonResult and data should be in List.
Using Entity Framework
using ChartDemo.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ChartDemo.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        // Using Entity Framework
        public JsonResult ChartFunction()
        {
            ArticlesEntitiesDB db = new ArticlesEntitiesDB();
            var data = db.ProductSales.ToList();
            return Json(data, JsonRequestBehavior.AllowGet);
        }
    }
}
Here we are going to use ADO.NET code to get data from database. Output will be same in both the cases.
Using ADO.NET Code
using ChartDemo.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ChartDemo.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        
        // Using ADO.NET Code
        public JsonResult ChartFunction()
        {
            string query = "select [Month],SalesCount from ProductSales";
            string constring = @"data source=#####;initial catalog=Articles;
            persist security info=True;user id=#####;password=#####;";
            List<ProductDetails> chartData = new List<ProductDetails>();
            using (SqlConnection con = new SqlConnection(constring))
            {
                using (SqlCommand cmd = new SqlCommand(query))
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.Connection = con;
                    con.Open();
                    using (SqlDataReader dr = cmd.ExecuteReader())
                    {
                        while (dr.Read())
                        {
                            ProductDetails pd = new ProductDetails();
                            pd.Month = dr["Month"].ToString();
                            pd.SalesCount = Convert.ToInt32(dr["SalesCount"]);
                            chartData.Add(pd);
                        }
                    }
                    con.Close();
                }
            }
            return Json(chartData, JsonRequestBehavior.AllowGet);
        }
        class ProductDetails
        {
            public string Month { get; set; }
            public Nullable<int> SalesCount { get; set; }
        }
    }
}
Adding View
Next step is to add view, right click on Index action method and add a new view without any model. Below is the code to draw chart using Google API.
First add two JavaScript reference files. First for jQuery support and second for google api reference.In options, you can specify the css and other properties highlighted in yellow. You can specify the different type of chart highlighted in green.
@{
    ViewBag.Title = "Draw Chart Using Google Chart API";
}

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>

<script type="text/javascript">
    google.load("visualization", "1", { packages: ["corechart"] });
    google.setOnLoadCallback(drawChart);
    function drawChart() {
        $.ajax({
            type: "POST",
            url: "/Home/ChartFunction",
            data: '{}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                var dt = new google.visualization.DataTable();
                dt.addColumn('string', 'Month');
                dt.addColumn('number', 'Sales Count');
                for (var i = 0; i < data.length; i++) {
                    dt.addRow([data[i].Month, data[i].SalesCount]);
                }
                var options = {
                    title: 'Product Sales Month Wise'
                };
                var chart = new google.visualization.ColumnChart($("#chart")[0]);
                chart.draw(dt, options);
            },
            failure: function (r) {
                alert(r.d);
            },
            error: function (r) {
                alert(r.d);
            }
        });
    }
</script>

<fieldset>
    <legend>Google Chart API IN ASP.NET MVC</legend>
    <div id="chart" style="height: 400px;width:900px;"></div>
</fieldset>
Below the output for column chart.
Draw Column Chart using Google Chart API in ASP.NET MVC

To draw pie chart change from ColumnChart to PieChart as shown below.
var chart = new google.visualization.PieChart($("#chart")[0]);
Draw Pie Chart using Google Chart API in ASP.NET MVC

To draw Doughnut chart, make chart type to PieChart and add pieHole: 0.5 as shown below
    var options = {
        title: 'Product Sales Month Wise',
        pieHole: 0.5
    };
    var chart = new google.visualization.PieChart($("#chart")[0]);
    chart.draw(dt, options);
Draw Doughnut Chart using Google Chart API in ASP.NET MVC

Draw Chart on Button click

Until now, we were drawing chart when view is loaded and now to draw chart on button click modify the view as shown below.
1) Add a button control as shown in green.
2) Attach Click event to this button using jQuery as shown in yellow.
3) Add "callback": drawChart as shown in blue.
Now when you will click on button then chart will be loaded.
<script type="text/javascript">
    $(function () {
        $("#btn").click(function () {
            google.load("visualization", "1", { packages: ["corechart"], "callback": drawChart });
            google.setOnLoadCallback(drawChart);
            function drawChart() {
                $.ajax({
                    type: "POST",
                    url: "/Home/ChartFunction",
                    data: '{}',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        var dt = new google.visualization.DataTable();
                        dt.addColumn('string', 'Month');
                        dt.addColumn('number', 'Sales Count');
                        for (var i = 0; i < data.length; i++) {
                            dt.addRow([data[i].Month, data[i].SalesCount]);
                        }
                        var options = {
                            title: 'Product Sales Month Wise',
                            pieHole: 0.5
                        };
                        var chart = new google.visualization.PieChart($("#chart")[0]);
                        chart.draw(dt, options);
                    },
                    failure: function (r) {
                        alert(r.d);
                    },
                    error: function (r) {
                        alert(r.d);
                    }
                });
            }
        });
    });
</script>

<input type="button" id="btn" value="Draw Chart"/>

<fieldset>
    <legend>Google Chart API IN ASP.NET MVC</legend>
    <div id="chart" style="height: 400px;width:900px;"></div>
</fieldset>
To draw Pie Chart in 3D make is3D :'true' in options.
    var options = {
        title: 'Product Sales Month Wise',
        pieHole: 0.5,
        is3D: 'true'
    };
Pie Chart in 3d look
Share:

Saturday, 19 August 2017

Draw (Implement) chart in ASP.NET MVC using chart class

In this article, I am going to explain you how to draw or implement chart in ASP.NET MVC using Chart Class (System.Web.Helpers) in C#. Below is the step by step tutorial.

Creating ASP.NET MVC 5 application

First of all create a new asp.net mvc 5 empty project. I am using visual studio 2013.
1) Open visual studio.
2) Go to File → New → Project.
3) Select Visual C# → Web → ASP.NET Web Application.
4) Give project name MVCChartDemo and click on OK as shown below.
Creating asp.net mvc 5 application
A new window will open as shown below. Select Empty Template, check on MVC and click on OK.
Selecting asp.net mvc 5 template

Adding Controller

Next step is to add controller. Add a new controller with name 'Home'. By default Index ActionResult will be generated. Add a new ActionResult method DrawChart as shown below.
Add namespace → System.Web.Helpers to support chart class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Helpers;
using System.Web.Mvc;

namespace MVCChartDemo.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult DrawChart()
        {
            new Chart(width: 500, height: 350)
            .AddTitle("Mobile Product Chart")
            .AddSeries(chartType: "column",
               xValue: new[] { "Apple", "HTC", "Samsung", "Nokia" },
               yValues: new[] { "50", "60", "80", "30" })
            .Write("png");
            return null;
        }
    }
}

Adding View

Next step is to add View. Right click on Index method and click on Add View. Set View name as Index, set Template as Empty(without model) and click on OK. Add below code to load DrawChart method.
<div style="margin-left:150px;">
    <table>
        <tr>
            <td><img src="@Url.Action("DrawChart")" alt="Draw Chart in ASP.NET MVC" /></td>
        </tr>
    </table>
</div>
Now run your application and you will see the below output as bar chart is generated.
Creating asp.net mvc 5 application
Now to draw Pie Chart set from chartType: "column" to chartType: "pie".
Draw pie chart in asp.net mvc

Applying Themes

Now we will apply various theme to make chart look nicer. To apply theme, change below line of code while creating chart object.
public ActionResult DrawChart()
{
    new Chart(width: 500, height: 350, theme:ChartTheme.Green) // change in-built theme here 
    .AddTitle("Mobile Product Chart")
    .AddSeries(chartType: "column",
       xValue: new[] { "Apple", "HTC", "Samsung", "Nokia" },
       yValues: new[] { "50", "60", "80", "30" })
    .Write("png");
    return null;
}
You can see the below chart after applying theme.
Applying inbuilt theme in chart

Applying Custom Themes

Now we can apply custom theme to chart.
public ActionResult DrawChart()
{
    string Mytheme = @"<Chart BackColor=""#99ffdb"" ForeColor=""Blue"">
                         <ChartAreas>
                            <ChartArea Name=""Default"" BackColor=""#ffedcc""></ChartArea>
                         </ChartAreas>
                       </Chart>";
    new Chart(width: 500, height: 300, theme: Mytheme)
    .AddTitle("Mobile Product Chart")
    .AddSeries(chartType: "column",
      xValue: new[] { "Apple", "HTC", "Samsung", "Nokia" },
      yValues: new[] { "50", "60", "80", "30" })
    .Write("png");
    return null;
}
Applying inbuilt custom theme in chart in mvc
You can customize your theme as per your requirement. Below is the another customize css theme.
public ActionResult DrawChart()
{
    string Mytheme = @"<Chart BackColor=""#D3DFF0"" BackGradientStyle=""TopBottom"" BackSecondaryColor=""White"" BorderColor=""26, 59, 105"" BorderlineDashStyle=""Solid"" BorderWidth=""2"" Palette=""None"" 
    PaletteCustomColors=""97,97,97; 209,98,96; 168,203,104; 142,116,178; 93,186,215; 255,155,83; 148,172,215; 217,148,147; 189,213,151; 173,158,196; 145,201,221; 255,180,138"">
      <ChartAreas>
          <ChartArea Name=""Default"" _Template_=""All"" BackColor=""64, 165, 191, 228"" BackGradientStyle=""TopBottom"" BackSecondaryColor=""White"" BorderColor=""64, 64, 64, 64"" BorderDashStyle=""Solid"" ShadowColor=""Transparent"" /> 
      </ChartAreas>
      <Legends>
          <Legend _Template_=""All"" BackColor=""Transparent"" Font=""Trebuchet MS, 8.25pt, style=Bold"" IsTextAutoFit=""False"" /> 
      </Legends>
      <BorderSkin SkinStyle=""Emboss"" /> 
    </Chart>";
    new Chart(width: 500, height: 300, theme: Mytheme)
    .AddTitle("Mobile Product Chart")
    .AddSeries(chartType: "column",
      xValue: new[] { "Apple", "HTC", "Samsung", "Nokia" },
      yValues: new[] { "50", "60", "80", "30" })
    .Write("png");
    return null;
}
Below is the output.
Applying inbuilt custom theme 2 in chart in mvc
Below is the another way to return chart from controller to view.
public ActionResult DrawChart()
{
    var chart = new Chart(width: 500, height: 350)
           .AddTitle("Mobile Product List")
           .AddSeries(chartType: "column",
             xValue: new[] { "Apple", "HTC", "Samsung", "Nokia" },
             yValues: new[] { "50", "60", "80", "30" })
           .GetBytes("png");
    return File(chart, "image/bytes");
}
Share:

Monday, 26 June 2017

Cascaded Dropdown in ASP.Net MVC using Entity Framework and jQuery ajax

In this article, I am going to teach you the basic cascading Dropdown in ASP.Net MVC using Entity Framework and jQuery Ajax. So, I am going to use Visual Studio 2013 ultimate, .net framework 4.5 and MVC version 4 and below is step by step tutorial.

Creating Database Table

First of all, we need to create database table. Below is the script to create two tables that are State Master and District Master and insert some dummy data into it.

create table tblStateMaster
(
StateId int,
Name varchar(100)
)
go
insert into tblStateMaster values(1,'Maharashtra')
insert into tblStateMaster values(2,'Gujarat')
go
create table tblDistrictMaster
(
DistId int,
StateId int,
Name varchar(100)
)
insert into tblDistrictMaster values(1,1,'Mumbai')
insert into tblDistrictMaster values(2,1,'Thane')
insert into tblDistrictMaster values(3,1,'Pune')
insert into tblDistrictMaster values(4,1,'Raigad')
go
insert into tblDistrictMaster values(5,2,'Ahmedabad')
insert into tblDistrictMaster values(6,2,'Rajkot')
insert into tblDistrictMaster values(7,2,'Gandhinagar')
insert into tblDistrictMaster values(8,2,'Vadodara')
Create table

Creating ASP.Net MVC Application

Now we need to create asp.net mvc application. Open Visual Studio 2013. Go to File --> New --> Project.. as shown below.

Creating a new asp.net mvc application

Go to Installed --> Templates --> Web --> Visual Studio 2012 and select .NET Framework 4.5 and ASP.NET MVC 4 Web Application as shown below.

Selecting asp.net mvc project

In the next window, select Empty template and click on OK and new MVC project will be created as shown below

Selecting asp.net mvc templateAsp.net mvc folder architecture

Adding Entity Framework

Now the next step is Entity Framework. Go to TOOLS --> Library Package Manager --> Manage NuGet Packages for Solution.. and a new window will open. Type and search for Entity Framework and click on Install button as shown below. Once installed successfully, you can check Entity Framework in references folder.

Adding Entity Framework
Installing Entity Framework

Adding Model

Now the next step is to add model. Go to Model and add two class files i.e. Data.cs and DataContext.cs. In Data.cs file, add below lines of code to map our database table to model object.

Adding modelAdding model and context class
[Table("tblStateMaster")]
public class State
{
    [Key]
    public int StateId { get; set; }
    public string Name { get; set; }
}

[Table("tblDistrictMaster")]
public class District
{
    [Key]
    public int DistId { get; set; }
    public int StateId { get; set; }
    public string Name { get; set; }
}

In DataContext.cs file, add two properties of type DbSet which will return DbSet of State and District.

Adding context class
public class DataContext : DbContext
{
    public DbSet<State> State { get; set; }
    public DbSet<District> District { get; set; }
}

Adding Connection String

Now add the connection string as shown below. Name of connection string should be same as context class name[DataContext].

Adding web.config file
Data context and web.config file connection string

Adding Controller

Now the next step is to add controller. Go to controller folder and add a new controller file named as DropDownController. Add below lines of code.

Adding controller class
public class DropDownController : Controller
{
    DataContext dc = new DataContext();

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

    public JsonResult GetState()
    {
        var stateData = dc.State.ToList().OrderBy(x => x.Name);
        return Json(stateData, JsonRequestBehavior.AllowGet);
    }

    public JsonResult GetDistrict(int StateId)
    {
        var districtData = dc.District.Where(x => x.StateId == StateId).OrderBy(x => x.Name);
        return Json(districtData);
    }
}

Adding jQuery File

Now the next step is to add jQuery file. You can download latest jQuery file from http://jquery.com/download/. Add jQuery file to your Scripts folder.

Adding View

Now the next step is to add View. Right click on Index ActionResult method, click Add View, give your View name as Index and do not click on strongly-typed view and click on Add. A DropDown folder will be added inside Views folder and an Index.cshtml file will be created.

Below is the code to Bind State Dropdown and District Dropdown using jQuery ajax method.

@{
    ViewBag.Title = "Index";
}

<script src="~/Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript">

    // bind State Dropdown when html is loaded
    $(document).ready(function () {
        $.ajax({
            type: "GET",
            url: "/DropDown/GetState",
            datatype: "Json",
            success: function (data) {
                $.each(data, function (index, value) {
                    $('#ddlState').append('<option value="' + value.StateId + '">' + value.Name + '</option>');
                });
            }
        });
    });
    // bind State Dropdown when html is loaded

    // bind district Dropdown on selection change of State
    $(document).ready(function () {
        $('#ddlState').change(function () {
            $('#ddlDistrict').empty();
            $.ajax({
                type: "POST",
                url: "/DropDown/GetDistrict",
                datatype: "Json",
                data: { StateId: $('#ddlState').val() },
                success: function (data) {
                    $('#ddlDistrict').append('<option value>--Select--</option>');
                    $.each(data, function (index, value) {
                        $('#ddlDistrict').append('<option value="' + value.DistId + '">' + value.Name + '</option>');
                    });
                }
            });
        });
    });
    // bind district dropdownlist on Dropdown change of State
</script>

<h2>Cascading DropDownList Example</h2>
<table style="font-family:Arial;">
    <tr>
        <td>
            @Html.DropDownList("ddlState", new SelectList(string.Empty, "Value", "Text"), "--Select--", null)
        </td>
        <td>
            @Html.DropDownList("ddlDistrict", new SelectList(string.Empty, "Value", "Text"), "--Select--", null)
        </td>
    </tr>
</table>

Once View is loaded successfully, you can see expected output below.

Cascading dropdown in asp.net mvc
Share:

Email Subscription

Subscribe to our newsletter to get the latest articles directly into your inbox

Blog Archive

Ads By Chitika