Friday, November 1, 2019

Delete Operations in Asp.net mvc using Ado.net Approach and Diff between ViewData, ViewBag and TempData


To delete a record from database



Delete store procedure in Sql Server



USE [MvcApplicaion]

GO

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

create PROCEDURE sp_DeleteEmployeeById

@EmpId int

AS

BEGIN

                    Delete From EmployeeModels where EmpId=@EmpId;

END



Now we go for the EmployeeContext.cs page and copy the below code



public int DeleteEmployeeDetailsById(int? id)

        {

            SqlCommand cmd = new SqlCommand("sp_DeleteEmployeeById", con);

            cmd.CommandType = CommandType.StoredProcedure;

            con.Open();

            cmd.Parameters.AddWithValue("@EmpId", id);

            object i = cmd.ExecuteNonQuery();

            int result = Convert.ToInt32(i);

            con.Close();

            return result;

        }    



 Now we go EmployeeController.cs page and copy the below code:



       public ActionResult Delete(int? id)

        {

            return View();

        }


        [HttpPost]

        [ActionName("Delete")]

        public ActionResult DeleteConform(int? id)

        {

            int i = db.DeleteEmployeeDetailsById(id);

            if (i > 0)

            {

                return RedirectToAction("index");

            }

            else

            {

                return View();

            }

        }



Add view For Delete Method in EmployeeController.cs Page then show one dialog box like below.



After click add code generate like below.



@model Asp.net_Approach.Models.EmployeeModel



@{

    ViewBag.Title = "Delete";

}



<h2>Delete</h2>



<h3>Are you sure you want to delete this?</h3>

<div>

    <h4>EmployeeModel</h4>

    <hr />

    <dl class="dl-horizontal">

        <dt>

            @Html.DisplayNameFor(model => model.EmpName)

        </dt>



        <dd>

            @Html.DisplayFor(model => model.EmpName)

        </dd>



        <dt>

            @Html.DisplayNameFor(model => model.EmpSalary)

        </dt>



        <dd>

            @Html.DisplayFor(model => model.EmpSalary)

        </dd>



    </dl>



    @using (Html.BeginForm()) {

        @Html.AntiForgeryToken()



        <div class="form-actions no-color">

            <input type="submit" value="Delete" class="btn btn-default" /> |

            @Html.ActionLink("Back to List", "Index")

        </div>

    }

</div>





After execute application when you call the get method it show like this:



After clicking the Delete link in above page it go delete conformation page


Clicking on Delete button calls the DeleteConform Action Method in EmployeeController.cs page above of the DeleteConform method one attribute [ActioName(“Delete”)] this method sends request to framework this particular record will be Deleted.



ViewData:

ViewData is a dictionary object that is derived from ViewDataDictionary class.

public ViewDataDictionary ViewData { get; set; }
ViewData is a property of Controller Base class.


ViewData is used to pass data from controller to corresponding view.

It’s life lies only during the current request.

If redirection occurs then it’s value becomes null.

It’s required typecasting for getting data and check for null values to avoid error.

Viewdata is used for transfering the data from controller to view for a corresponded or single request



Syntax:  

        Public ActionResult Index()

        {
                   Viewdata[“EmpDetails”]=”Supriya”;
         }

Example:  

 public ActionResult Index()
        {
            List<string> obj = new List<string>();
            obj.Add("pratiusha");
            obj.Add("deepti");
            obj.Add("Nagini");
            obj.Add("Anusha");
            ViewData["Student"] = obj;
            return View();
        }

<ul>
    @foreach (string item in ViewData["Student"] as List<string>)
    {

        <li>@item</li>
    }
</ul> 


ViewBage:

ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.


Basically it is a wrapper around the ViewData and also used to pass data from controller to corresponding view.

public Object ViewBag { get; }
ViewBag is a property of ControllerBase class.


It’s life also lies only during the current request.

If redirection occurs then it’s value becomes null.

It doesn’t required typecasting for getting data.


Syntax

       Public ActionResult Index()

      {
                 ViewBag.EmpDetails =”Supriya”;
       }

we are creating model in model folder

  public class Employee
    {
        public int Empid { get; set; }
        public string EmpName { get; set; }

        public string Department { get; set; }
    }


--->
creating Controller

  public ActionResult Index()
        {
            Employee emp = new Employee();
            emp.Empid = 1;
            emp.EmpName = "prfatiusha";
            emp.Department = "IT";

            ViewBag.Details = emp;
            return View();
        }

under view

<ul>
   <li> @ViewBag.Details.Empid</li>
    <li> @ViewBag.Details.EmpName</li>
    <li> @ViewBag.Details.Department</li>
</ul>

or

@{
    ViewBag.Title = "Index";
    var myfellow = ViewBag.Details;
}

<h2>Index</h2>

<ul>
    <li> @myfellow.Empid</li>
    <li> @myfellow.EmpName</li>
    <li> @myfellow.Department</li>
</ul> 


TempData:

 TempData is a dictionary object that is derived from TempDataDictionary class and stored in short lives session.

public TempDataDictionary TempData { get; set; }
TempData is a property of ControllerBase class.


TempData is used to pass data from current request to subsequent request (means redirecting from one page to another).

It’s life is very short and lies only till the target view is fully loaded.

It’s required typecasting for getting data and check for null values to avoid error.

It is used to store only one time messages like error messages, validation messages. To persist data with TempData refer this article: Persisting Data with TempData

TempData:it is used to transfer the data from one  controller to another controller then you can use tempdata

Tempdata is also Tempdictionary object
Tempdata["key"]=value;

Tempdata is used to retain the values by two ways

1)keep method: it is used to retain the values which is present in tempdata
               return type is void

 Tempdata.keep();

2)peek method:
it is used for getting the object by using the key and will retain the values
by not allowing the key to be deleted
 Tempdata.peek("key");both accessing value and for retaing the value

public ActionResult Index()
        {
            TempData["Student"] = "Pratiusha";
            return RedirectToAction("About");
        }
        public ActionResult About()
        {
            var b = TempData.Peek("Student");
            var c = TempData.Peek("Student");
            ViewData["b"] = b;
            ViewData["c"] = c;
           
            return View();
        }




No comments:

Post a Comment