Pages

Thursday, August 1, 2013

Entity Framework-Bind Data In Grid usind Stored Procedure -MVC4

Bind Data In Grid usind Stored Procedure: 

Step1: Create Stored Procedure..

Step2: Create edmx File and Add Your table and Stored procddures...

Step3:Genrate  Code Generation Form edmx file...


Step4: This For Only Get data from SP.


Step5:  

Ofter Genrate Your Model1.Context.tt From .edmx file...

Add /Edit/Delete Operation From Stored Procedure:
  set Parameters: 
  public virtual int xp_Potential_AddUpdateDelete(Nullable<int> potentialId, string potentialTitle, Nullable<int> potenOwnr_EmpID, string accountName, string accountId, string contactName, string contactId, string potential_Type, string primary_CampaginSrc, Nullable<System.DateTime> close_Date, Nullable<int> stageId, string probablity, string approxAmount_Product, string approxAmount_Services, string total_ApproxAmount, string nextStep, string description, Nullable<int> leadSourceId, Nullable<int> prev_TaskID_Active, Nullable<int> accnt_ActivityId, Nullable<int> user, Nullable<int> opration, ObjectParameter status)
        {
            var potentialIdParameter = potentialId.HasValue ?
                new ObjectParameter("PotentialId", potentialId) :
                new ObjectParameter("PotentialId", typeof(int));
   
            var potentialTitleParameter = potentialTitle != null ?
                new ObjectParameter("PotentialTitle", potentialTitle) :
                new ObjectParameter("PotentialTitle", typeof(string));
   
            var potenOwnr_EmpIDParameter = potenOwnr_EmpID.HasValue ?
                new ObjectParameter("PotenOwnr_EmpID", potenOwnr_EmpID) :
                new ObjectParameter("PotenOwnr_EmpID", typeof(int));
   
            var accountNameParameter = accountName != null ?
                new ObjectParameter("AccountName", accountName) :
                new ObjectParameter("AccountName", typeof(string));
   
            var accountIdParameter = accountId != null ?
                new ObjectParameter("AccountId", accountId) :
                new ObjectParameter("AccountId", typeof(string));
   
            var contactNameParameter = contactName != null ?
                new ObjectParameter("ContactName", contactName) :
                new ObjectParameter("ContactName", typeof(string));
   
            var contactIdParameter = contactId != null ?
                new ObjectParameter("ContactId", contactId) :
                new ObjectParameter("ContactId", typeof(string));
   
            var potential_TypeParameter = potential_Type != null ?
                new ObjectParameter("Potential_Type", potential_Type) :
                new ObjectParameter("Potential_Type", typeof(string));
   
            var primary_CampaginSrcParameter = primary_CampaginSrc != null ?
                new ObjectParameter("Primary_CampaginSrc", primary_CampaginSrc) :
                new ObjectParameter("Primary_CampaginSrc", typeof(string));
   
            var close_DateParameter = close_Date.HasValue ?
                new ObjectParameter("Close_Date", close_Date) :
                new ObjectParameter("Close_Date", typeof(System.DateTime));
   
            var stageIdParameter = stageId.HasValue ?
                new ObjectParameter("StageId", stageId) :
                new ObjectParameter("StageId", typeof(int));
   
            var probablityParameter = probablity != null ?
                new ObjectParameter("Probablity", probablity) :
                new ObjectParameter("Probablity", typeof(string));
   
            var approxAmount_ProductParameter = approxAmount_Product != null ?
                new ObjectParameter("ApproxAmount_Product", approxAmount_Product) :
                new ObjectParameter("ApproxAmount_Product", typeof(string));
   
            var approxAmount_ServicesParameter = approxAmount_Services != null ?
                new ObjectParameter("ApproxAmount_Services", approxAmount_Services) :
                new ObjectParameter("ApproxAmount_Services", typeof(string));
   
            var total_ApproxAmountParameter = total_ApproxAmount != null ?
                new ObjectParameter("Total_ApproxAmount", total_ApproxAmount) :
                new ObjectParameter("Total_ApproxAmount", typeof(string));
   
            var nextStepParameter = nextStep != null ?
                new ObjectParameter("NextStep", nextStep) :
                new ObjectParameter("NextStep", typeof(string));
   
            var descriptionParameter = description != null ?
                new ObjectParameter("Description", description) :
                new ObjectParameter("Description", typeof(string));
   
            var leadSourceIdParameter = leadSourceId.HasValue ?
                new ObjectParameter("LeadSourceId", leadSourceId) :
                new ObjectParameter("LeadSourceId", typeof(int));
   
            var prev_TaskID_ActiveParameter = prev_TaskID_Active.HasValue ?
                new ObjectParameter("Prev_TaskID_Active", prev_TaskID_Active) :
                new ObjectParameter("Prev_TaskID_Active", typeof(int));
   
            var accnt_ActivityIdParameter = accnt_ActivityId.HasValue ?
                new ObjectParameter("Accnt_ActivityId", accnt_ActivityId) :
                new ObjectParameter("Accnt_ActivityId", typeof(int));
   
            var userParameter = user.HasValue ?
                new ObjectParameter("user", user) :
                new ObjectParameter("user", typeof(int));
   
            var oprationParameter = opration.HasValue ?
                new ObjectParameter("opration", opration) :
                new ObjectParameter("opration", typeof(int));
   
            return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("xp_Potential_AddUpdateDelete", potentialIdParameter, potentialTitleParameter, potenOwnr_EmpIDParameter, accountNameParameter, accountIdParameter, contactNameParameter, contactIdParameter, potential_TypeParameter, primary_CampaginSrcParameter, close_DateParameter, stageIdParameter, probablityParameter, approxAmount_ProductParameter, approxAmount_ServicesParameter, total_ApproxAmountParameter, nextStepParameter, descriptionParameter, leadSourceIdParameter, prev_TaskID_ActiveParameter, accnt_ActivityIdParameter, userParameter, oprationParameter, status);
        }


And Get Data Function:
  public virtual ObjectResult<xp_getAllPotential_Result> xp_getAllPotential()
        {
            ((IObjectContextAdapter)this).ObjectContext.MetadataWorkspace.LoadFromAssembly(typeof(xp_getAllPotential_Result).Assembly);
   
            return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<xp_getAllPotential_Result>("xp_getAllPotential");
        }


Controllers Class:


Add/Edit/Delete for Sp:

     [HttpPost]
        public ActionResult CreateEditPotential(CS_Potential mCust, string Command)
        {
            // Validate the model being submitted
            int oprat =  Convert.ToInt32(Command);

            if (!ModelState.IsValid)
            {

                return PartialView("_Potential", mCust);

            }
                   tbl_Potential mobjcust=new tbl_Potential();

                   if (oprat == 0)
                   {
                       mobjcust.PotentialId =  0;
                   }
                   else
                   {
                       mobjcust.PotentialId = mCust.PotentialId;
                       oprat = 0;
                   }
                    mobjcust.PotentialTitle=mCust.PotentialTitle;
                    mobjcust.PotenOwnr_EmpID=mCust.PotenOwnr_EmpID;
                    mobjcust.AccountName=mCust.AccountName;
                    mobjcust.AccountId=mCust.AccountId;
                    mobjcust.ContactName=mCust.ContactName;
                    mobjcust.ContactId=mCust.ContactId;
                    mobjcust.Potential_Type=mCust.Potential_Type;
                    mobjcust.Primary_CampaginSrc = mCust.Primary_CampaginSrc;

                    mobjcust.Close_Date=null;//mCust.Close_Date
                    mobjcust.StageId=null;//mCust.StageId
                    mobjcust.Probablity="";//mCust.Probablity
                    mobjcust.ApproxAmount_Product="";//mCust.ApproxAmount_Product
                    mobjcust.ApproxAmount_Services="";//mCust.ApproxAmount_Services
                    mobjcust.Total_ApproxAmount="";//mCust.Total_ApproxAmount
                    mobjcust.NextStep="";//mCust.NextStep
                    mobjcust.Description="";//mCust.Description
                    mobjcust.LeadSourceId=null;//mCust.LeadSourceId
                    mobjcust.Prev_TaskID_Active = 1;// null;//mCust.Prev_TaskID_Active
                    mobjcust.Accnt_ActivityId=null;//mCust.Accnt_ActivityId
                    mobjcust.CreatedBy=1;//mCust.CreatedBy
                  
                    int check = mobjModel.Potential_AddUpdateDelete(mobjcust, oprat);
                    if (check == 2 || check == 3 || check == 4)
                {
                    TempData["Msg"] = "Data has been saved succeessfully";
                    ModelState.Clear();
                    return RedirectToAction("TaskPotentialGrid", "C_Potential");
                }

            return PartialView("_Potential");
        }


   public ActionResult Edit(int id)
        {
            var data = mobjModel.GetPotential1(id);

            if (Request.IsAjaxRequest())
            {
                CS_Potential cust = new CS_Potential();
                cust.PotentialTitle = data.PotentialTitle;
                cust.PotentialId = data.PotentialId;
                cust.PotenOwnr_EmpID = data.PotenOwnr_EmpID;
                cust.AccountName = data.AccountName;
                cust.AccountId = data.AccountId;
                cust.ContactName = data.ContactName;
                cust.ContactId = data.ContactId;
                cust.Potential_Type = data.Potential_Type;
                cust.Primary_CampaginSrc = data.Primary_CampaginSrc;


                ViewData["EmpTitle"] = GetUsers();

                ViewBag.IsUpdate = true;
                return View("_Potential", cust);
            }
            else

                return View(data);
        }


        public ActionResult Delete(int id)
        {
            tbl_Potential mobjcust = new tbl_Potential();
            int oprat = 1;
            mobjcust.PotentialId= id;
            mobjcust.Prev_TaskID_Active = 18;
           
            int check = mobjModel.Potential_AddUpdateDelete(mobjcust,oprat);
            if (check==4)
            {
                TempData["Msg"] = "Data has been Deleted succeessfully";
                ModelState.Clear();
                return RedirectToAction("TaskPotentialGrid", "C_Potential");
            }
            else
            {
                return PartialView("_Potential");
            }

        } 





   Get Data Function For Bind :

    public ActionResult TaskPotentialGrid(int page = 1, string sort = "name", string sortDir = "ASC")
        {
            const int pageSize = 5;
            var totalRows = mobjModel.CountPotential();

            sortDir = sortDir.Equals("desc", StringComparison.CurrentCultureIgnoreCase) ? sortDir : "asc";

            var validColumns = new[] { "TaskStatusId", "TaskStatus", "CreatedDate", "IsActive" };
            if (!validColumns.Any(c => c.Equals(sort, StringComparison.CurrentCultureIgnoreCase)))
                sort = "TaskStatusId";
           
            var task = mobjModel.GetPotentialPage(page, pageSize, "it." + sort + " " + sortDir);

            var data = new PagedCustomerModel()
            {
                TotalRows = totalRows,
                PageSize = pageSize,
                Task = task
            };
            return View(data);
        }




Model Class Code:

   Add/Edit/Delete for Sp:

public int Potential_AddUpdateDelete(tbl_Potential Pt,int opration)
        {
            if (Pt.PotentialId == 0 && opration==0) //Add
            {
                AllOpration(Pt, opration);
                return 2;
            }
            else if (Pt.PotentialId > 0 && opration==1) //Delete
            {
                AllOpration(Pt, opration);
                return 4;
            }
            else if (Pt.PotentialId > 0 && opration==0)  //update
            {
                AllOpration(Pt, opration);
                return 3;
            }
            else
            {
                return 1;
            }

        } 

 public bool AllOpration(tbl_Potential Pt, int oprat)
        {

            System.Data.Entity.Core.Objects.ObjectParameter result = new System.Data.Entity.Core.Objects.ObjectParameter("Status", typeof(int));
            result.Value = DBNull.Value;

            entities.xp_Potential_AddUpdateDelete(Pt.PotentialId, Pt.PotentialTitle, Pt.PotenOwnr_EmpID, Pt.AccountName, Pt.AccountId, Pt.ContactName, Pt.ContactId, Pt.Potential_Type, Pt.Primary_CampaginSrc, Pt.Close_Date, Pt.StageId, Pt.Probablity, Pt.ApproxAmount_Product, Pt.ApproxAmount_Services, Pt.Total_ApproxAmount, Pt.NextStep, Pt.Description, Pt.LeadSourceId, Pt.Prev_TaskID_Active, Pt.Accnt_ActivityId, Pt.CreatedBy, oprat, result);

            if (result.Equals(2) || result.Equals(3) || result.Equals(4))
            {
                return true;
            }

            else
            {
                return false;
            }
            //return false;
        } 


Get data For .edmx file

   public List<CS_Potential> GetPotentialPage(int pageNumber, int pageSize, string searchCriteria)
        {
            if (pageNumber < 1)
                pageNumber = 1;

           // return entities.xp_getAllPotential();
                //  .OrderBy(searchCriteria)
                //.Skip((pageNumber - 1) * pageSize)
              //.Take(pageSize)
              //.ToList();



                entities=new eCRM_MastersEntities1();
                var data =
                    (from pt in entities.xp_getAllPotential()
                     select new CS_Potential
                     {
                         PotentialId = pt.PotentialId,
                         PotentialTitle = pt.PotentialTitle,
                         Name=pt.Name,
                         AccountName=pt.AccountName,
                         ContactName = pt.ContactName,
                         ContactId = pt.ContactId,
                         AccountId=pt.AccountId
                     }
                    ).ToList();
                return data;
              
        
                 }



View Page:


@model BAL.MS_PotentialMaster

@{
    ViewBag.Title = "M_Potential";
   
     WebGrid grid = new WebGrid(rowsPerPage: Model.PageSize);
     if(Model.TotalRows>0)
     {
     grid.Bind(Model.Potential,
               autoSortAndPage: false,
               rowCount: Model.TotalRows);
     }
}


<script src="../../Scripts/jquery.validate.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>

<script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-ui-1.8.20.min.js" type="text/javascript"></script>


<link href="../../Content/themes/base/minified/jquery-ui.min.css" rel="stylesheet" type="text/css" />
<link href="../../Content/Site.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
    $(document).ready(function () {

        $("#CreateCustomer").live("click", function (e) {
            // e.preventDefault(); use this or return false
            var url = $(this).attr('href');
            $("#dialog-edit").dialog({
                title: 'Create Potential Stage',
                autoOpen: false,
                resizable: false,
                height: 200,
                width: 400,
                show: { effect: 'drop', direction: "up" },
                modal: true,
                draggable: true,
                open: function (event, ui) {
                    $(this).load(url);

                },
                close: function (event, ui) {
                    $(this).dialog('close');
                }
            });

            $("#dialog-edit").dialog('open');
            return false;
        });

        $(".editDialog").live("click", function (e) {
            // e.preventDefault(); use this or return false
            var url = $(this).attr('href');
            $("#dialog-edit").dialog({
                title: 'Edit Potential Stage',
                autoOpen: false,
                resizable: false,
                height: 200,
                width: 400,
                show: { effect: 'drop', direction: "up" },
                modal: true,
                draggable: true,
                open: function (event, ui) {
                    $(this).load(url);

                },
                close: function (event, ui) {
                    $(this).dialog('close');
                }
            });

            $("#dialog-edit").dialog('open');
            return false;
        });

        $(".confirmDialog").live("click", function (e) {

            // e.preventDefault(); use this or return false
            var url = $(this).attr('href');

            $("#dialog-confirm").dialog({
                autoOpen: false,
                resizable: false,
                height: 170,
                width: 350,
                show: { effect: 'drop', direction: "up" },
                modal: true,
                draggable: true,
                buttons: {
                    "OK": function () {
                        $(this).dialog("close");
                        window.location = url;

                    },
                    "Cancel": function () {
                        $(this).dialog("close");

                    }
                }
            });
            $("#dialog-confirm").dialog('open');
            return false;
        });

        $(".viewDialog").live("click", function (e) {
            // e.preventDefault(); use this or return false
            var url = $(this).attr('href');
            $("#dialog-view").dialog({
                title: 'View Potential Stage',
                autoOpen: false,
                resizable: false,
                height: 150,
                width: 400,
                show: { effect: 'drop', direction: "up" },
                modal: true,
                draggable: true,
                open: function (event, ui) {
                    $(this).load(url);

                },
                buttons: {
                    "Close": function () {
                        $(this).dialog("close");

                    }
                },
                close: function (event, ui) {
                    $(this).dialog('close');
                }
            });

            $("#dialog-view").dialog('open');
            return false;
        });

        $("#btncancel").live("click", function (e) {
            // location.reload(true);
            $("#dialog-edit").dialog('close');

        });
    });  
</script>

@using (Html.BeginForm("M_Potential", "M_Potential", FormMethod.Post, new { enctype = "multipart/form-data" }))
{ 
   
     
    <table style="margin-top:10px; border:1 solid Gray; padding-top:50;" cellpadding="0" cellspacing="0">
      <tr>
      <td colspan="2">
       <div style="color: Red; font-weight:bold;">
    @TempData["msg"] 
 
  <br />
  </div>
      </td>
      </tr>
    <tr>
    <td>
  
  
    @Html.LabelFor(m => m.PotentialStage)
        
    </td>
    <td>
     @Html.TextBoxFor(m => m.PotentialStage)
   
   <span style=" color:Red;">
  
    @Html.ValidationMessageFor(m => m.PotentialStage)
   </span>
   

    </td>
   
    </tr>

    <tr>
    <td></td>
    <td align="left" >
    <input type="submit" value="Add potential Stage" id="btnSubmit" />
   
    </td>
    </tr>
    </table>
    
    <table>
    <tr>
    <td colspan="2">
    <div>
     @if (Model.PotentialStageId > 0)
     {
   @* <table style="margin-top:10px; border:1 solid Gray; padding-top:50;" cellpadding="0" cellspacing="0">
    <tr>
     <td class="editor-label">
            @Html.LabelFor(model => model.PotentialStage)
        </td>
        <td class="editor-field">
            @Html.DisplayTextFor(model => model.PotentialStage)
        </td>
    </tr>
    <tr>
    <td class="editor-label">
            @Html.LabelFor(model => model.CreatedDate)
        </td>
        <td class="editor-field">
            @Html.DisplayTextFor(model => model.CreatedDate)
        </td>
       </tr>

      </table>
    *@
 
     }
    </div>
   
 @if (Model.TotalRows > 0)
 {
     <br />
    @grid.GetHtml(
    fillEmptyRows: false,
    tableStyle:"WebGrid",
  
         headerStyle: "webgrid-header",
         footerStyle: "webgrid-footer",
               alternatingRowStyle: "webgrid-alternating-row",
         selectedRowStyle: "webgrid-selected-row",
               rowStyle: "webgrid-row-style", htmlAttributes: new { id = "grid" },
    mode: WebGridPagerModes.All,
            firstText: "<< First",
            previousText: "< Prev",
            nextText: "Next >",
            lastText: "Last >>",
            columns: new[] {
       
        grid.Column("PotentialStageId", header: "Stage ID", canSort: false),
        grid.Column("PotentialStage",  header: "Stage Name",
        format: @<text> @Html.ActionLink((string)item.PotentialStage, "View", new { id = item.PotentialStageId }, new { @class = "viewDialog" })</text>
          ),
        grid.Column("CreatedDate", header: "Created Date",format: (item) => string.Format("{0:dd-MMM-yyyy}", item.CreatedDate)),
        grid.Column("", header: "Actions",format: @<text>
        @Html.ActionLink("Edit", "Edit", new { id = item.PotentialStageId }, new { @class = "editDialog"/*, data_dialog_id = "edit-Dialog"*/ })
 |      @Html.ActionLink("Delete", "Delete", new { id = item.PotentialStageId }, new { @class = "confirmDialog" })
         </text>
        )
    })
 }
 else
 {
       <p>No data found.</p>  
          
 }
   
    </td>
   
    </tr>



   
    </table>
    <div id="dialog-confirm" style="display: none">
    <p>
        <span class="ui-icon ui-icon-alert" style="float: left; margin: 0 7px 20px 0;"></span>
        Are you sure to delete ?
    </p>
</div>
<div id="dialog-edit" style="display: none">
</div>
<div id="dialog-view" style="display: none">
</div>
  
   

}


Hope It will Help You...Enj..

Code Written by Anjum Syend and me...




Grid-in MVC4

Bind Grid In MVC:

Step 1:
Controllers Page:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using eCRM_MastersLib;
using BAL;
using eCRM_Entity;

namespace eCRM.Controllers.eCRM_Masters
{
    public class M_DesignationController : Controller
    {
        //
        // GET: /G_Designation/
        Designation mobjModel = new Designation();

        eCRM_MastersEntities1 entities = new eCRM_MastersEntities1();


        [HttpGet]
        public ActionResult _Designation()
        {
            return View();
        }

      
        public ActionResult WebGrid(int page = 1, string sort = "name", string sortDir = "ASC")
        {
            const int pageSize = 5;
            var totalRows = mobjModel.CountDesignation();

            sortDir = sortDir.Equals("desc", StringComparison.CurrentCultureIgnoreCase) ? sortDir : "asc";

            var validColumns = new[] { "DesginationId", "DesignationName", "CreatedDate", "IsActive" };
            if (!validColumns.Any(c => c.Equals(sort, StringComparison.CurrentCultureIgnoreCase)))
                sort = "DesignationId";

            var designation = mobjModel.GetDesignationPage(page, pageSize, "it." + sort + " " + sortDir);

            var data = new PagedCustomerModel()
            {
                TotalRows = totalRows,
                PageSize = pageSize,
                Designation = designation
            };
            return View(data);
        }


        public class PagedCustomerModel
        {
            public int TotalRows { get; set; }
            public IEnumerable<tbl_Designation> Designation { get; set; }
            public int PageSize { get; set; }
        }


        public ActionResult Create()
        {
            if (Request.IsAjaxRequest())
            {

                ViewBag.IsUpdate = false;
                return View("_Designation");
            }
            else

                return View();
        }

        public ActionResult View(int id)
        {
            var data = mobjModel.GetDesignation1(id);
            if (Request.IsAjaxRequest())
            {
                MS_DesignationMaster cust = new MS_DesignationMaster();
                cust.DesignationName = data.DesignationName;
                //cust.Name = data.Name;
                //cust.Address = data.Address;
                //cust.ContactNo = data.ContactNo;

                return View("_ViewDesignation", cust);
            }
            else

                return View(data);
        }


        public ActionResult Edit(int id)
        {
            var data = mobjModel.GetDesignation1(id);

            if (Request.IsAjaxRequest())
            {
                MS_DesignationMaster cust = new MS_DesignationMaster();
                cust.DesignationName = data.DesignationName;
                cust.DesginationId = data.DesginationId;
                //cust.Name = data.Name;
                //cust.Address = data.Address;
                //cust.ContactNo = data.ContactNo;

                ViewBag.IsUpdate = true;
                return View("_Designation", cust);
            }
            else

                return View(data);
        }


        public ActionResult Delete(int id)
        {
            tbl_Designation mobjcust = new tbl_Designation();
            mobjcust.DesginationId = id;// mCust.DesginationId;
            //mobjcust.Address = mCust.Address;
            //mobjcust.ContactNo = mCust.ContactNo;
            //mobjcust.Name = mCust.Name;

            bool check = mobjModel.DeleteDesignation(mobjcust);
            if (check)
            {
                TempData["Msg"] = "Data has been Deleted succeessfully";
                ModelState.Clear();
                return RedirectToAction("WebGrid", "M_Designation");
            }
            else
            {
                return PartialView("_Designation");
            }
            //bool check = mobjModel.DeleteDesignation(id);
            //var data = mobjModel.GetDesignation();
            //return RedirectToAction("WebGrid");
        }


        [HttpPost]
        public ActionResult CreateEditDesignaion(MS_DesignationMaster mCust, string Command)
        {
            // Validate the model being submitted

            if (!ModelState.IsValid)
            {

                return PartialView("_Designation", mCust);

            }

            else if (Command == "Save")
            {
                tbl_Designation mobjcust = new tbl_Designation();

                tbl_Designation isexist = entities.tbl_Designation.Where(x => x.DesignationName == mCust.DesignationName).FirstOrDefault();


                if (isexist != null)
                {
                    TempData["Msg"] = "Designation is allready exists";
                    ModelState.Clear();
                    return RedirectToAction("WebGrid", "M_Designation");

                }
                else
                {
                    mobjcust.DesignationName = mCust.DesignationName;
                    mobjcust.IsActive = true;
                    //mobjcust.Address = mCust.Address;
                    //mobjcust.ContactNo = mCust.ContactNo;
                    //mobjcust.Name = mCust.Name;

                    bool check = mobjModel.CreateDesignation(mobjcust);
                    if (check)
                    {
                        TempData["Msg"] = "Data has been saved succeessfully";
                        ModelState.Clear();
                        return RedirectToAction("WebGrid", "M_Designation");
                    }
                }
            }

            else if (Command == "Update")
            {
                tbl_Designation mobjcust = new tbl_Designation();
                mobjcust.DesignationName = mCust.DesignationName;
                mobjcust.DesginationId = mCust.DesginationId;
                //mobjcust.Address = mCust.Address;
                //mobjcust.ContactNo = mCust.ContactNo;
                //mobjcust.Name = mCust.Name;

                bool check = mobjModel.UpdateDesignation(mobjcust);
                if (check)
                {
                    TempData["Msg"] = "Data has been updated succeessfully";
                    ModelState.Clear();
                    return RedirectToAction("WebGrid", "M_Designation");
                }

            }

            return PartialView("_Designation");
        }

    }
}






Step2:

Model Code:

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

using System.Text.RegularExpressions;
using System.Linq.Expressions;
using eCRM_Entity;
using BAL;

namespace eCRM_MastersLib
{
    public class Designation : IDisposable
    {
        bool status;
        private readonly eCRM_MastersEntities1 entities = new eCRM_MastersEntities1();

        public IEnumerable<tbl_Designation> GetDesignation()
        {
            return entities.tbl_Designation.Where(m => m.IsActive==true).ToList();
        }

        public IEnumerable<tbl_Designation> GetDesignationPage(int pageNumber, int pageSize, string searchCriteria)
        {
            if (pageNumber < 1)
                pageNumber = 1;

            return entities.tbl_Designation
                //  .OrderBy(searchCriteria)
                //.Skip((pageNumber - 1) * pageSize)
              .Take(pageSize)
              .ToList();
        }

        public class PagedCustomerModel
        {
            public int TotalRows { get; set; }
            public IEnumerable<tbl_Designation> Designation { get; set; }
            public int PageSize { get; set; }
        }

        public int CountDesignation()
        {
            return entities.tbl_Designation.Count();
        }

        public void Dispose()
        {
            entities.Dispose();
        }

        public tbl_Designation GetDesignation1(int mDesgID)
        {
            return entities.tbl_Designation.Where(m => m.DesginationId == mDesgID).FirstOrDefault();
        }

        public bool CreateDesignation(tbl_Designation des)
        {
            try
            {
                using (var db = new eCRM_MastersEntities1())
                {

                    var dc = db.tbl_Designation.Create();
                    dc.DesignationName = des.DesignationName;
                    // dc.DesginationId = Designationdetails.DesginationId;
                    dc.CreatedBy = 1;//int.Parse(des.CreatedBy.ToString());
                    dc.CreatedDate = Convert.ToDateTime(System.DateTime.Now.ToShortDateString());
                    db.tbl_Designation.Add(dc);
                    db.SaveChanges();
                    //status = true;

                    //        return RedirectToAction("index", "index");
                }
                return true;
            }
            catch (Exception mex)
            {
                return false;
            }
        }

        public bool UpdateDesignation(tbl_Designation mDesignation)
        {
            try
            {
                tbl_Designation data = entities.tbl_Designation.Where(m => m.DesginationId == mDesignation.DesginationId).FirstOrDefault();

                data.DesignationName = mDesignation.DesignationName;
                //data.Address = mCustomer.Address;
                //data.ContactNo = mCustomer.ContactNo;
                entities.SaveChanges();
                return true;
            }
            catch (Exception mex)
            {
                return false;
            }
        }


        public bool DeleteDesignation(tbl_Designation mDesignation)
        {
            try
            {
                tbl_Designation data = entities.tbl_Designation.Where(m => m.DesginationId == mDesignation.DesginationId).FirstOrDefault();
                data.IsActive = false;
                //entities.tbl_Designation.DeleteObject(data);
                entities.SaveChanges();
                return true;
            }
            catch (Exception mex)
            {
                return false;
            }
        }


        public bool CreateEditDesignation(tbl_Designation des, string Command)
        {
            // Validate the model being submitted

            //if (!ModelState.IsValid)
            //{

            //    return PartialView("_Designation", mCust);

            //}

            if (Command == "Save")
            {
                using (var db = new eCRM_MastersEntities1())
                {

                    var dc = db.tbl_Designation.Create();
                    dc.DesignationName = des.DesignationName;
                    dc.IsActive = des.IsActive;
                    // dc.DesginationId = Designationdetails.DesginationId;
                    dc.CreatedBy = 1;//int.Parse(des.CreatedBy.ToString());
                    dc.CreatedDate = Convert.ToDateTime(System.DateTime.Now.ToShortDateString());
                    db.tbl_Designation.Add(dc);
                    db.SaveChanges();
                    status = true;

                    //        return RedirectToAction("index", "index");
                }
            }

            else if (Command == "Update")
            {
                tbl_Designation mobjcust = new tbl_Designation();
                Designation ab = new Designation();
                // mobjcust.CustID = mCust.CustID;
                // mobjcust.Address = mCust.Address;
                // mobjcust.ContactNo = mCust.ContactNo;
                mobjcust.DesignationName = des.DesignationName;

                bool check = ab.UpdateDesignation(mobjcust);
                if (check)
                {
                    //TempData["Msg"] = "Data has been updated succeessfully";
                    //ModelState.Clear();
                    // return RedirectToAction("WebGrid", "G_Designation");
                    status = true;
                }
                else
                {
                    status = false;
                }

                //}

                //return PartialView("_Customer");
            }
            return status;

        }

        void IDisposable.Dispose()
        {
            throw new NotImplementedException();
        }
    }
}







Step3:

View Code:

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
    ViewBag.Title = "Designation Master";
    }

@{
    eCRM_MastersLib.Designation b = new eCRM_MastersLib.Designation();
  
    WebGrid grid = new WebGrid();
    grid.Bind(b.GetDesignation() );
           
 
}


<link href="../../Content/themes/base/minified/jquery-ui.min.css" rel="stylesheet" type="text/css" />
<script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-ui-1.8.20.min.js" type="text/javascript"></script>
<link href="../../Content/Site.css" rel="stylesheet" type="text/css" />

<script type="text/javascript">
    $(document).ready(function () {

        $("#CreateCustomer").live("click", function (e) {
            // e.preventDefault(); use this or return false
            var url = $(this).attr('href');
            $("#dialog-edit").dialog({
                title: 'Create TaskStatus',
                autoOpen: false,
                resizable: false,
                height: 355,
                width: 400,
                show: { effect: 'drop', direction: "up" },
                modal: true,
                draggable: true,
                open: function (event, ui) {
                    $(this).load(url);

                },
                close: function (event, ui) {
                    $(this).dialog('close');
                }
            });

            $("#dialog-edit").dialog('open');
            return false;
        });

        $(".editDialog").live("click", function (e) {
            // e.preventDefault(); use this or return false
            var url = $(this).attr('href');
            $("#dialog-edit").dialog({
                title: 'Edit TaskStatus',
                autoOpen: false,
                resizable: false,
                height: 355,
                width: 400,
                show: { effect: 'drop', direction: "up" },
                modal: true,
                draggable: true,
                open: function (event, ui) {
                    $(this).load(url);

                },
                close: function (event, ui) {
                    $(this).dialog('close');
                }
            });

            $("#dialog-edit").dialog('open');
            return false;
        });

        $(".confirmDialog").live("click", function (e) {

            // e.preventDefault(); use this or return false
            var url = $(this).attr('href');

            $("#dialog-confirm").dialog({
                autoOpen: false,
                resizable: false,
                height: 170,
                width: 350,
                show: { effect: 'drop', direction: "up" },
                modal: true,
                draggable: true,
                buttons: {
                    "OK": function () {
                        $(this).dialog("close");
                        window.location = url;

                    },
                    "Cancel": function () {
                        $(this).dialog("close");

                    }
                }
            });
            $("#dialog-confirm").dialog('open');
            return false;
        });

        $(".viewDialog").live("click", function (e) {
            // e.preventDefault(); use this or return false
            var url = $(this).attr('href');
            $("#dialog-view").dialog({
                title: 'View TaskStatus',
                autoOpen: false,
                resizable: false,
                height: 250,
                width: 400,
                show: { effect: 'drop', direction: "up" },
                modal: true,
                draggable: true,
                open: function (event, ui) {
                    $(this).load(url);

                },
                buttons: {
                    "Close": function () {
                        $(this).dialog("close");

                    }
                },
                close: function (event, ui) {
                    $(this).dialog('close');
                }
            });

            $("#dialog-view").dialog('open');
            return false;
        });

        $("#btncancel").live("click", function (e) {
            // location.reload(true);
            $("#dialog-edit").dialog('close');

        });
    });  
</script>

<div style="height:10px;background-color:Yellow;">
</div>
<h2>
    Designation Master</h2>
<br />
<div style="color: Green; font-weight: bold">
    @TempData["msg"]
</div>
<br />
@grid.GetHtml(
    fillEmptyRows: false,
       tableStyle: "webgrid",
    headerStyle: "webgrid-header",
    footerStyle: "webgrid-footer",
    alternatingRowStyle: "webgrid-alternating-row",
    selectedRowStyle: "webgrid-selected-row",
        rowStyle: "webgrid-row-style", htmlAttributes: new { id = "grid" },
    mode: WebGridPagerModes.All,
            firstText: "<< First",
            previousText: "< Prev",
            nextText: "Next >",
            lastText: "Last >>",
    columns: new[] {
       
       
       
        grid.Column("DesginationId",
                    header: "DesginationId", canSort: false),
         grid.Column("DesignationName",
                    header: "DesignationName",
                    format: @<text>
@Html.ActionLink((string)item.DesignationName, "View", new { id = item.DesginationId }, new { @class = "viewDialog" })</text>
                    ),
       @*grid.Column("Address"),*@
       @* grid.Column("ContactNo",
                    header: "Contact No"
        ),*@
        grid.Column("",
                    header: "Actions",
                    format: @<text>
@Html.ActionLink("Edit", "Edit", new { id = item.DesginationId }, new { @class = "editDialog"/*, data_dialog_id = "edit-Dialog"*/ })
|
@Html.ActionLink("Delete", "Delete", new { id = item.DesginationId }, new { @class = "confirmDialog" })
</text>
        )
})
<br />

<a id="CreateCustomer" href="M_Designation\Create" class="Create">Create Designation</a>
<div id="dialog-confirm" style="display: none">
    <p>
        <span class="ui-icon ui-icon-alert" style="float: left; margin: 0 7px 20px 0;"></span>
        Are you sure to delete ?
    </p>
</div>
<div id="dialog-edit" style="display: none">
</div>
<div id="dialog-view" style="display: none">
</div>





   Enj...Hope it will help You..