Showing posts with label MVC Tutorial. Show all posts
Showing posts with label MVC Tutorial. Show all posts

Thursday, 20 April 2017

ViewModel Example In MVC ASP.Net With bootstrap

What is ViewModel in MVC ?
Answer: ViewModel contain fields that are represented in the view.It allow you to shape multiple entities from one or more data models or sources into a single object, optimized for consumption and rendering by the view.

In this tutorials i am going to showing demo how to use of ViewModel class in MVC ASP.Net.





In this demo I used flowing version of framework
  • Using Visual studio 2012 MVC 4 version.
  • Sql Server 2012.
  • AutoMapper DLL references  
  • For css using bootstrap and jquery
  • Entity framework (4.4.0.0) references  


Step:1
Create a Three table in sql server database. The three table name as

  • y_category_master
  • y_vendor_master
  • y_Product_Master

CREATE TABLE [dbo].[y_category_master] (
    [CategoryID]   INT          IDENTITY (1, 1) NOT NULL,
    [CategoryName] VARCHAR (50) NULL,
    CONSTRAINT [PK_y_category_master] PRIMARY KEY CLUSTERED ([CategoryID] ASC)
);

GO
CREATE TABLE [dbo].[y_vendor_master] (
    [venderId]   INT          IDENTITY (1, 1) NOT NULL,
    [venderName] VARCHAR (50) NULL,
    CONSTRAINT [PK_y_vendor_master] PRIMARY KEY CLUSTERED ([venderId] ASC)
);

GO
CREATE TABLE [dbo].[y_Product_Master] (
    [ProductId]  INT             IDENTITY (1, 1) NOT NULL,
    [Name]       VARCHAR (50)    NULL,
    [Price]      DECIMAL (18, 2) NULL,
    [CategoryID] INT             NULL,
    [VendorID]   INT             NULL,
    CONSTRAINT [PK_y_Product_Master] PRIMARY KEY CLUSTERED ([ProductId] ASC),
    CONSTRAINT [FK_y_Product_Master_y_category_master] FOREIGN KEY ([CategoryID]) REFERENCES [dbo].[y_category_master] ([CategoryID]),
    CONSTRAINT [FK_y_Product_Master_y_vendor_master] FOREIGN KEY ([VendorID]) REFERENCES [dbo].[y_vendor_master] ([venderId])
);

GO
CREATE NONCLUSTERED INDEX [IX_FK_y_Product_Master_y_category_master]
    ON [dbo].[y_Product_Master]([CategoryID] ASC);

GO
CREATE NONCLUSTERED INDEX [IX_FK_y_Product_Master_y_vendor_master]
    ON [dbo].[y_Product_Master]([VendorID] ASC);


Step:2 Create Entity Data Model to connect to database

Right-click on your project in Solution Explorer then click on ADD New ADO.NET Entity Data Model. name as "Product.edmx". Create database connection with the help of Entity framework
And drag & drop all three table in Entity modal design.



Step:3 Reffrence the AutoMapper DLL to your projects

Right Click on your project in Solution Explorer then select Manage NuGet Packages.search AutoMapper and install it.


Step:4 Add Model class

Here I created product modal partial class in Modal Folder with name Product.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ViewModelProj.Models
{
    public partial class Product
    {
        public string Name { get; set; }
        public decimal Price { get; set; }
        public int CategoryID { get; set; }
        public int VendorID { get; set; }
 
    }

    public partial class Product
    {
        public string CategoryName { get; set; }
        public string VendorName { get; set; }
    }
}

Step:5 Add ViewModel class

Create new folder in project View_Model. In this folder right click and add class with name ProductViewModel.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ViewModelProj.Models;
using System.Web.Mvc;

namespace ViewModelProj.View_Model
{
    public class ProductViewModel
    {
        public Product product { get; set; }
        public SelectList VendorList { get; set; }
        public SelectList CategoryList { get; set;}
    }
}


Step:6 Add Controller 
In Controller folder open the 'HomeController' and put the code given bellow.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ViewModelProj.Models;
using ViewModelProj.View_Model;
using AutoMapper;

namespace ViewModelProj.Controllers
{
    public class HomeController : Controller
    {  
        TestEntities db = new TestEntities();
        public ActionResult Index()
        {
            List<Product> ProVModal = new List<Product>();
            using (TestEntities dc = new TestEntities())
            {
                var v = (from a in dc.y_Product_Master
                         join b in dc.y_category_master on a.CategoryID equals b.CategoryID
                         join c in dc.y_vendor_master on a.VendorID equals c.venderId
                         select new Product
                         {
                             Name = a.Name,
                             Price= (decimal)a.Price,
                             CategoryName= b.CategoryName,
                             VendorName = c.venderName
                         }).OrderBy(x => x.Name).ToList();
                ProVModal = v;
             
            }
            return View(ProVModal);
        }

        public ActionResult AddProduct()
        {
            ProductViewModel objProductViewModel = new ProductViewModel();
            var category = db.y_category_master;
            var vendor = db.y_vendor_master;

            objProductViewModel.CategoryList = new SelectList(category, "CategoryID", "CategoryName");
            objProductViewModel.VendorList = new SelectList(vendor, "venderId", "venderName");

            return View(objProductViewModel);
        }

        public ActionResult SaveProduct(ProductViewModel objProductViewModel)
        {        
            Mapper.CreateMap<Product,y_Product_Master>();
            y_Product_Master obj1 = Mapper.Map<Product, y_Product_Master>(objProductViewModel.product);
            db.y_Product_Master.Add(obj1);
            db.SaveChanges();

            return View();
        }

    }
}

Step:7 Adding View
Add three View against the controler. I added three view which given bellow as

Index.cshtml : This View showing all the product list in grid.
AddProduct.cshtml : This View use for add new product in system.
SaveProduct.cshtml : This View use shwoing Message to successfully product added.

@model IEnumerable<ViewModelProj.Models.Product>
@{
    ViewBag.Title = "Index";
}

<link href="~/Content/Bootstrap/bootstrap.css" rel="stylesheet" />

<h2 style="margin-left: 20px">All Product List</h2>
<p style="margin-left: 20px">
    @Html.ActionLink("Create New", "AddProduct")
</p>

 <div class="row" style="margin-left: 20px">
     <div class="form-group">
            <div class="col-md-6">
<table  class="col-md-12 table-bordered table-striped table-condensed cf" style="margin-left: 20px">
    <thead class="cf" style="border: 1px solid #ccc;">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Price)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.CategoryName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.VendorName)
        </th>
        <th></th>
    </tr>
        </thead>
    <tbody style="border: 1px thin black">
@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Price)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.CategoryName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.VendorName)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
            @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
            @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
        </td>
    </tr>
}
         </tbody>
</table>
</div>
         </div>
     </div>


AddProduct.cshtml
@model ViewModelProj.View_Model.ProductViewModel

@{
    ViewBag.Title = "AddProduct";
}

<h2 style="margin-left: 20px">AddProduct</h2>

@using (Html.BeginForm("SaveProduct","Home",FormMethod.Post)) {
    @Html.ValidationSummary(true)

    <div class="row" >
         <div class="col-xs-12 col-sm-12 col-md-12 ">
                    &nbsp;
                </div>
         <div>    
    </div>

         <div class="col-md-12">
        <table style="width:40%; margin-left: 20px" class="table-condensed" border="1">
        <tr>
            <td>
                <div class="row" >
                <div class="col-xs-12 col-sm-6 col-md-6">
                    <div class="editor-label">
                        Product Name:                    
                    </div>
                </div>
                <div class="col-xs-12 col-sm-6 col-md-6">
                    <div class="editor-field">
                        @Html.TextBoxFor(model => model.product.Name, new { @class="form-control", placeholder="Please Enter Product Name"})
                        @Html.ValidationMessageFor(model => model.product.Name, "Please Enter ProductName", new { @class = "text-danger" })
                    </div>
                </div>
              </div>

                <div class="row" >
               <div class="col-xs-12 col-sm-6 col-md-6">
                    <div class="editor-label">
                        Price:
                    </div>
                </div>
                <div class="col-xs-12 col-sm-6 col-md-6">
                    <div class="editor-field">

                        @Html.TextBoxFor(model => model.product.Price, new { @class="form-control", placeholder="Please Enter product Price"})
                        @Html.ValidationMessageFor(model => model.product.Price, "Please Enter product Price", new { @class = "text-danger" })
                     </div>
                </div>
                    </div>

                <div class="row" >
                <div class="col-xs-12 col-sm-6 col-md-6">
                    <div class="editor-label">
                     Select Category:
                    </div>
                </div>
                <div class="col-xs-12 col-sm-6 col-md-6">
                    <div class="editor-field">
                        @Html.DropDownListFor(model => model.product.CategoryID, Model.CategoryList, "-- Select One --" , new { @style = "width:100%", @class="dropdown-header" })
                        @Html.ValidationMessageFor(model => model.CategoryList, "Please Select Department Location", new { @class = "text-danger" })
                     </div>
                </div>
                    </div>

                <div class="row" >
                 <div class="col-xs-12 col-sm-6 col-md-6">
                    <div class="editor-label">
                      Select Vendor:
                    </div>
                </div>
                <div class="col-xs-12 col-sm-6 col-md-6">
                    <div class="editor-field">
                        @Html.DropDownListFor(model => model.product.VendorID, Model.VendorList, "-- Select One --" , new { @style = "width:100%", @class="dropdown-header" })
                        @Html.ValidationMessageFor(model => model.VendorList, "Please Select Department Location", new { @class = "text-danger" })
                     </div>
                </div>
                     </div>

                <div class="row" >
                <div class="col-xs-12 col-sm-12 col-md-12 " style="align-items:center">
                    <br />
                    <br />
                 
                     <button type="submit"  value="SAVE"  class="btn btn-success btn-group-lg"  >
                            <span class="glyphicon glyphicon-plus"></span> SAVE
                      </button>      
                </div>
              </div>
            </td>
        </tr>
    </table>
 </div>
</div>
}
 <br />
<div>
    <div class="row" >
                <div class="col-xs-12 col-sm-12 col-md-12 " style="margin-left: 20px" >
                           @Html.ActionLink("Back to List", "Index")
                    </div>
        </div>
    </div>

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


SaveProduct.cshtml
@{
    ViewBag.Title = "SaveProduct";
}

<h2>Product Saved Successfully</h2>

<p>
    @Html.ActionLink("List of Prduct", "Index")
</p>


Conclusion : 
                     In this way you can use viewmodal class in mvc. Hope this article will helpful for you.

Thursday, 13 April 2017

Paging and Sorting in MVC4 Using PagedList



In this tutorials i am going to showing Paging and Sorting in MVC4 Using PagedList . For this  Am using 

Step i am going to do here

  1. using Visual studio 2012 MVC 4 version.
  2. Sql Server 2012.
  3. For css using bootstrap and jquery
  4. Entity framework (4.4.0.0) references  
  5. Reffrence the PagedList.mvc in project

Step:1 

Create a table in sql server database and create store procedure (script given bellow)

CREATE TABLE [dbo].[DepartmentLocation](
[LocationId] [int] IDENTITY(1,1) NOT NULL,
[LocationName] [nvarchar](50) NULL,
[Address] [nvarchar](50) NULL,
[City] [nvarchar](50) NULL,
[Pincode] [nvarchar](50) NULL,
[PhoneNo] [nvarchar](50) NULL,
[CountryID] [nvarchar](50) NULL,
PRIMARY KEY CLUSTERED 
(
[LocationId] 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

Create PROCEDURE [dbo].[Sp_Get_DepartmentList]
AS
Begin
SELECT DL.LocationId,
      DL.LocationName,
  DL. Address,
  DL.City,
  DL.Pincode,
  DL.CountryID,
      C.CountryName
from Country C inner join DepartmentLocation DL On C.CountryID=DL.CountryID

End

Step:2 Create Entity Data Model to connect to database

Right-click on your project in Solution Explorer then click on ADD New ADO.NET Entity Data Model. name as "MyContactBookEntities" ...



Step:3 Reffrence the Pagedlist dll and css to your projects

on your project in Solution Explorer then select Manage NuGet Packages.search Pagedlist.mvc  and install it.





Step:3

Add new Controller with name 'DepartmentLocationController.cs' and put the code given bellow.

DepartmentLocationController.cs

using AutoMapper;
using MVCContactBook.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PagedList;

namespace MVCContactBook.Controllers
{
      public class DepartmentLocationController : BaseController
          {
           public ActionResult GetDepartmentLocationList(string sortOn, string orderBy, string                                pSortOn, int? page)
           {          
            int recordsPerPage = 10;
            if (!page.HasValue)
            {
                page = 1; // set initial page value
                if (string.IsNullOrWhiteSpace(orderBy) || orderBy.Equals("asc"))
                {
                    orderBy = "desc";
                }
                else
                {
                    orderBy = "asc";
                }
            }          
            if (!string.IsNullOrWhiteSpace(sortOn) && !sortOn.Equals(pSortOn, StringComparison.CurrentCultureIgnoreCase))
            {
                orderBy = "asc";
            }

            ViewBag.OrderBy = orderBy;
            ViewBag.SortOn = sortOn;
        
            MyContactBookEntities dc = new MyContactBookEntities();
            var list = dc.Sp_Get_DepartmentList().AsQueryable();
                     
            switch (sortOn)
            {
                case "LocationName":
                    if (orderBy.Equals("desc"))
                    {
                        list = list.OrderByDescending(p => p.LocationName);
                    }
                    else
                    {
                        list = list.OrderBy(p => p.LocationName);
                    }
                    break;
                case "Address":
                    if (orderBy.Equals("desc"))
                    {
                        list = list.OrderByDescending(p => p.Address);
                    }
                    else
                    {
                        list = list.OrderBy(p => p.Address);
                    }
                    break;
                case "City":
                    if (orderBy.Equals("desc"))
                    {
                        list = list.OrderByDescending(p => p.City);
                    }
                    else
                    {
                        list = list.OrderBy(p => p.City);
                    }
                    break;                
                default:
                    list = list.OrderBy(p => p.LocationId);
                    break;
            }

            var finalList = list.ToList().ToPagedList(page.Value, recordsPerPage);
            return View(finalList);
        }
 }

}

Step:4

Add View against the action method name 'GetDepartmentLocationList' and put the code given bellow.

View
GetDepartmentLocationList.cshtml

@using PagedList;
@using PagedList.Mvc;
@model IPagedList<MVCContactBook.Sp_Get_DepartmentList_Result>
@{
    ViewBag.Title = "GetDepartmentLocationList";
}

<script src="~/Scripts/jquery-3.1.1.js"></script>
    <script src="~/Scripts/bootstrap.min.js"></script>
    <script>
        $(document).ready(function () {
            hideColumn = function (column) {
                $('tr').each(function () {
                    $(this).find('td,th').eq(column).hide();
                });
            };
            hideColumn(0);

        });
    </script>


<h2>Department Location List</h2>

<p>
    @Html.ActionLink("Create New", "AddNewLocation")
</p>

 <div id="no-more-tables">
<table  class="col-md-12 table-bordered table-striped table-condensed cf">
     <thead class="cf" style="border: 1px solid #ccc;">
    <tr>
        <th  class="numeric">
            @*@Html.DisplayNameFor(model => model.LocationId)*@
        </th>
        <th  style="text-align:center;">
            
            @Html.ActionLink("Location", "GetDepartmentLocationList", new { sortOn ="LocationName", orderBy = ViewBag.OrderBy, pSortOn = ViewBag.SortOn })
        </th>
         <th style="text-align:center;">
            @Html.ActionLink("Address", "GetDepartmentLocationList", new { sortOn ="Address", orderBy = ViewBag.OrderBy, pSortOn = ViewBag.SortOn })
        </th>
         <th style="text-align:center;">
            @Html.ActionLink("City", "GetDepartmentLocationList", new { sortOn ="City", orderBy = ViewBag.OrderBy, pSortOn = ViewBag.SortOn })
        </th>
        <th style="text-align:center;">
            Pincode
        </th>
      
        <th style="text-align:center;">
            Country
        </th>
        <th>Edit</th>
        <th>Delete</th>
    </tr>
         </thead>
      <tbody style="border: 1px thin black">

         
@foreach (var item in Model)
{
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.LocationId)
        </td>
        <td style="text-align:center;">
            @Html.DisplayFor(modelItem => item.LocationName)
        </td>
        <td style="text-align:center;">
            @Html.DisplayFor(modelItem => item.Address)
        </td>
        <td style="text-align:center;">
            @Html.DisplayFor(modelItem => item.City)
        </td>
        <td style="text-align:center;">
            @Html.DisplayFor(modelItem => item.Pincode)
        </td>
      
        <td style="text-align:center;">
            @Html.DisplayFor(modelItem => item.CountryName)
        </td>
        <td style="text-align:center;">
            @Html.ActionLink(" ", "Edit", new { id = item.LocationId }, new { @class = "glyphicon glyphicon-edit", title = "Edit" }) 
            </td>

            <td style="text-align:center;">
            @Html.ActionLink(" ", "Delete", new { id = item.LocationId }, new { @class = "glyphicon glyphicon-trash", title = "Delete" })        
            
        </td>
    </tr>

}
          </tbody>
 </table>
    <div class="pagedList">
        @Html.PagedListPager(Model, page => Url.Action("GetDepartmentLocationList", new { page,
sortOn = ViewBag.SortOn, orderBy = ViewBag.OrderBy, pSortOn = ViewBag.SortOn }), PagedListRenderOptions.ClassicPlusFirstAndLast)
    </div>
   </div>

Saturday, 25 March 2017

Insert, Update, Delete operation in MVC-4 with Entity Framework.

In This Session  I am going to describe Insert, Update, Delete operation in MVC-4 with Entity Framework.

Here I am using visual stdio 2012 (framework 4.5) , SQL server 2012 express and Entity Framework

So Lets start