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...




No comments:

Post a Comment