Saturday 7 May 2016

ASP.NET MVC GridView Display and Simple Display Project Using SQL Database

ASP.NET MVC GridView Display and Simple Display Project Using SQL Database.

In this project I am using SQL database to insert employee data using asp.net mvc coding. And displaying the records in 2 different methods.
1) Normal table structure,
2) Grid View form.
Soon I will do an explanation video on this topic. Based on user request I will upload the entire project if anyone wants. You can visit our video on youtube http://youtube.com/8bitzs

Find the screens shots in the last page of Blog

Screens:

Models:
1)    emp.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;  //used to do the validations

namespace GridMVC.Models
{
    public class emp
    {
        [Required]
        public int emp_code { get; set; }
        [Required]
        public string emp_name { get; set; }

        [Required]
     // [StringLength(2, ErrorMessage = "The age must be 2 digits !", MinimumLength = 2)]
        public int age { get; set; }
        public double salary { get; set; }
        public int phone { get; set; }
    }
}

************************************************************
Views: (Inside Home Folder)
1   1)    Index.cshtml

@{
    ViewBag.Title = "Home Page";
}
@section featured {
    <section class="featured">
        <div class="content-wrapper">
            <hgroup class="title">
                <h2>@ViewBag.Message</h2>
            </hgroup>
            <p>
                To learn more about ASP.NET MVC visit
                <a href="http://youtube.com/8bitzs" target="_blank" title="8bitzs">http://youtube.com/8bitzs</a>.
                The page features <mark>videos, tutorials, and samples</mark> to help you get the most from ASP.NET MVC.
                If you have any questions about ASP.NET MVC Drop comments in
                <a href="http://clearosapps.blogspot.com" target="_blank" title="Clearosapps">our Blog</a>.
            </p>
        </div>
    </section>
}

<ul style="font-size:large">
    <li>@Html.ActionLink("Insert Record", "insert", "Home")</li>
    <li>@Html.ActionLink("Display", "display", "Home")</li>
    <li>@Html.ActionLink("GridView", "grid", "Home")</li>
    </ul>
*****************************************************
2)    insert.cshtml

@model GridMVC.Models.emp

@{
    ViewBag.Title = "insert";
}

<h2>insert</h2>

@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>emp</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.emp_code)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.emp_code)
            @Html.ValidationMessageFor(model => model.emp_code)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.emp_name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.emp_name)
            @Html.ValidationMessageFor(model => model.emp_name)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.age)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.age)
            @Html.ValidationMessageFor(model => model.age)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.salary)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.salary)
            @Html.ValidationMessageFor(model => model.salary)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.phone)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.phone)
            @Html.ValidationMessageFor(model => model.phone)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

*********************************************************************

3)    display.cshtml  //normal view

@model GridMVC.Models.emp[]
@using System.Data;

@{
    ViewBag.Title = "display";
}

<h2>display</h2>

<fieldset>
    <legend>emp</legend>

    <table style="border:groove;border-color:black">
        <tr>
            <th style="border:groove;">
               
                    Emp Code
               
            </th>
            <th style="border:groove;">
               
                    Name
               
            </th>
            <th style="border:groove;">
              
                    Age
               
            </th>
            <th style="border:groove;">
               
                    Salary
               
            </th>
            <th style="border:groove;">
               
                    Mobile No
              
            </th>
           
        </tr>

        @for (int i = 0; i < Model.Count(); i++)
        {
           
              <tr>
                <th style="border:groove;">

            @Html.DisplayFor(model => model[i].emp_code)
       
        </th>
       
        <th style="border:groove;">

            @Html.DisplayFor(model => model[i].emp_name)
      
        </th>
        
        <th style="border:groove;">

            @Html.DisplayFor(model => model[i].age)
      
        </th>
       
        <th style="border:groove;">

            @Html.DisplayFor(model => model[i].salary)
       
        </th>
       
        <th style="border:groove;">

            @Html.DisplayFor(model => model[i].phone)
       
        </th>
       
      
        </tr>
        }
        </table>

</fieldset>
<p>
    @Html.ActionLink("Edit", "Edit", new { /* id=Model.PrimaryKey */ }) |
    @Html.ActionLink("Back to List", "Index")
</p>

*************************************************************

4)    grid.cshtml

@model IEnumerable<GridMVC.Models.emp>

@{
    ViewBag.Title = "grid";
    WebGrid grid = new WebGrid(Model);
}

<h2>grid</h2>

<fieldset>
    <legend>emp</legend>

    @grid.GetHtml(columns: new[] {
        grid.Column("emp_code"),
        grid.Column("emp_name"),
        grid.Column("age"),
        grid.Column("salary"),
        grid.Column("phone"),
})

  
</fieldset>
<p>
    @Html.ActionLink("Edit", "Edit", new { /* id=Model.PrimaryKey */ }) |
    @Html.ActionLink("Back to List", "Index")
</p>

***********************************************************
5)    _Layout.cshtml (inside Shared folder)

 <!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>@ViewBag.Title - My ASP.NET MVC Application</title>
        <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
        <meta name="viewport" content="width=device-width" />
        @Styles.Render("~/Content/css")
        @Scripts.Render("~/bundles/modernizr")
    </head>
    <body>
        <header>
            <div class="content-wrapper">
                <div class="float-left">
                    <p class="site-title"><a href="@Url.Action("Index", "Home")">
    <img src="@Url.Content("~/Images/8bitzs.png")" style="width:20%;height:20%;"/>
</a></p>
                </div>
                <div class="float-right">
                    <section id="login">
                        @Html.Partial("_LoginPartial")
                    </section>
                    <nav>
                        <ul id="menu">
                            <li>@Html.ActionLink("Home", "Index", "Home")</li>
                            <li>@Html.ActionLink("About", "About", "Home")</li>
                            <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                        </ul>
                    </nav>
                </div>
            </div>
        </header>
        <div id="body">
            @RenderSection("featured", required: false)
            <section class="content-wrapper main-content clear-fix">
                @RenderBody()
            </section>
        </div>
        <footer>
            <div class="content-wrapper">
                <div class="float-left">
                    <p>&copy; @DateTime.Now.Year - My ASP.NET MVC Application</p>
                </div>
            </div>
        </footer>

        @Scripts.Render("~/bundles/jquery")
        @RenderSection("scripts", required: false)
    </body>
</html>

********************************************************************
Controllers:
1    1)    HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.SqlClient;
using System.Data;
using GridMVC.Models;

namespace GridMVC.Controllers
{
    public class HomeController : Controller
    {
        SqlConnection con = new SqlConnection("data source=(LocalDB)\\v11.0;attachdbfilename=|DataDirectory|\\mydb.mdf;");

        [HttpPost]
        public ActionResult insert(emp e)
        {
            string emp_name=e.emp_name;
            int emp_code = e.emp_code, age = e.age,  phone = e.phone;
            double salary = e.salary;
            con.Open();
            SqlCommand cmd = new SqlCommand("insert into emp values ("+emp_code+",'"+emp_name+"',"+age+","+salary+","+phone+")", con);
            cmd.ExecuteNonQuery();
           
            return View("Index");
        }

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

        public ActionResult display()
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("select * from emp", con);
            DataTable dt = new DataTable();
            SqlDataAdapter adp = new SqlDataAdapter(cmd);
            adp.Fill(dt);
            emp[] e = new emp[dt.Rows.Count];
            int i = 0;
            foreach (DataRow dr in (dt).Rows)
            {
                e[i] = new emp();
                e[i].emp_code = Convert.ToInt32((string)dr[0]);
                e[i].emp_name  = (string)dr[1];
                e[i].age=  (int)dr[2];
                e[i].salary = (int)dr[3];
                e[i].phone = (int)dr[4];
                i = i + 1;
            }
            return View(e);
        }

        public ActionResult grid()
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("select * from emp", con);
            DataTable dt = new DataTable();
            SqlDataAdapter adp = new SqlDataAdapter(cmd);
            adp.Fill(dt);
            emp[] e = new emp[dt.Rows.Count];
            List<emp>listemp=new List<emp>();

            int i = 0;
            foreach (DataRow dr in (dt).Rows)
            {
                e[i] = new emp();
                e[i].emp_code = Convert.ToInt32((string)dr[0]);
                e[i].emp_name = (string)dr[1];
                e[i].age = (int)dr[2];
                e[i].salary = (int)dr[3];
                e[i].phone = (int)dr[4];
                listemp.Add(e[i]);
                i = i + 1;
            }
            var data = listemp;

            return View(data);
        }


        public ActionResult Index()
        {
            ViewBag.Message = "This Asp.net MVC Project saves data in to the database and retrive the data and showing in grid form, Where user can sort the data";

            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your app description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}

***************************************************************************
SQL Table Structure:
create table emp (emp_code varchar (10), emp_name varchar (25),age int,salary int,phone int)

Screen Shots:
1)Home Page :



2)Insert Record to database



3)Simple Display using Table:



4)Grid View


Grid Sorting while clicking on the headings




No comments:

Post a Comment

Share It

Followers