Creating a simple ASP.NET MVC Project (Part 2) Edit and Delete

Panthmadan
Posted by in ASP.NET MVC category on for Beginner level | Points: 250 | Views : 8863 red flag
Rating: 4.5 out of 5  
 2 vote(s)

In this article will continue with Select, Delete and Update functions.
Recommendation
Read Creating a simple ASP.NET MVC project (Part 1) in 23 steps before this article.
Read the first part of this article here.

Contents

Introduction :

SELECT METHOD :

Step 24 :

Step 25 :

Step 26 :

Step 27 :

DELETE METHOD :

Step 28 :

Step 29 :

Step 30 :

Step 31:

UPDATE METHOD :

Step 32 :

Step 33 :

Step 34 :

Step 35 :

Step 36 :

Conclusion :

Introduction :

Hello everyone I hope you could do the Simple project for Insert operation in using Entity Framework from my previous ASP.NET MVC article.

I am excited to continue this article further adding some extra parts to it. So that we can say we have a complete basic Form with Insert, Update, Select and Delete with the Database Connection using ASP.NET MVC. I am sure that even you will be able to demo it on your side. I am trying to make this project as simple as possible with basic fundamentals of HTTP Methods.

In this article will continue with Select, Delete and Update Functions for our Form Records which is also commonly known as CRUD operations. I would like to stress on the point that please do make an attempt to demo this project and not only read the article. And I can assure you this will really help out in some part of your live project.

Download source code for the article from this link

In case you are facing issues i would recommend you to watch visually the Learn MVC series video from the below youtube video

Starting with the SELECT METHOD :

We know that whenever we have a target we need to have a plan for that. So the same applies here in programming.

In Select Method the aim is to View the record of a particular student. So here I am making an approach for creating a unique hyperlink for Select using basic tags. So every record you insert will have its unique hyperlink for View. And that hyperlink will pass that particular record to the Action Controller and will return the View for the selected record.

Step 24 :

So now we need to make some changes in Index.cshtml file that will generate a hyperlink for the new record for View.

@using MyApp.Models
@model List<University>
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div> 
        <h1><a href="Create"> Add  a New University </a></h1> <br />
        <table border="1">
            <tr>
                <th>Reg No</th>
                <th>University Name</th>
                <th>University City</th>
            </tr>
            @foreach (University item in Model)
            {
                <tr>
                    <td>@item.RegNo</td>
                    <td> @item.Name </td>
                    <td> @item.City </td>
                    <td> <a href="ViewUniversity/@item.ID">View</a> | @*Generate a hyperlink View action for a particular record*@
                        
                    </td>
                </tr>
            }
        </table>
    </div>
</body>
</html>

Step 25 :

When we click on the Hyperlink we have to fetch the data on a new page. So will create a new page named as “ViewUniversity.cshtml” . All the html files will be inside the View Directory of University Folder. Then only the University Controller can access those Views.

@model MyApp.Models.University 

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>ViewUniversity</title>
</head>
<body>
    <div> 
        <h4>University</h4>
        <hr />
        
            <b>Reg No -></b>
            @Model.RegNo <br />   @*Fetching the Reg No from the record*@
            <b>University Name -></b>
            @Model.Name <br />  @*Fetching the Name from the record*@
            <b>University City -></b>
            @Model.City <br /> @*Fetching the City from the record*@
        
    </div>
    <p>
        <a href="/University/Index">HomePage</a>  @*Generating a Link to Hit the Index Page*@
    </p>
</body>
</html>

The above page will fetch the data from the Model Class University which is passed along with the ViewUniversity() Method.

Step 26 :

We have added the hyperlink for the View, we have also created a page for that view. Next is to fetch the record using the Action Method and passing it to the ViewUniversity.cshtml.

Will add a ActionResult method named “ViewUniversity()” in our UniversityController.cs

publicActionResultViewUniversity(int Id) // Passing the Primary Key of the record
        {
UniversityDALudal = newUniversityDAL(); //Creating an object of DAL
University u = udal.Universities.Find(Id); //Using DAL Find() method to fectch the record
return View("ViewUniversity",u); //Passing the Model to the ViewUnviverty.cshtml Page
        }

Step 27 :

Lets rebuild the project and execute it.

To make sure we have new data in database you can delete the previous records using DROP command.

Add some new records to the Database. (I have added two new records)

We can see that a View hyperlink is generated.

As soon as we click the View for a record it hits the ViewUniversity() method and invokes the ViewUniversity.cshtml page with its records.

The below is a view for the first record with a HomePage link to hit the Index Page.

DELETE METHOD :

In Delete Method the aim is to delete the record of a particular student. So here I am making an approach for creating a unique hyperlink for Delete using basic tags. So every record you insert will have its unique hyperlink for delete. And that hyperlink will pass that particular record to the Action Controller and will return the view after the deletion.

Step 28 :

So now we need to make some changes in Index.cshtml file that will generate a hyperlink for the new record for Delete.

@using MyApp.Models
@model List<University>
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div> 
        <h1><a href="Create"> Add  a New University </a></h1> <br />
        <table border="1">
            <tr>
                <th>Reg No</th>
                <th>University Name</th>
                <th>University City</th>
            </tr>
            @foreach (University item in Model)
            {
                <tr>
                    <td>@item.RegNo</td>
                    <td> @item.Name </td>
                    <td> @item.City </td>
                    <td> <a href="ViewUniversity/@item.ID">View</a> | @*Generate a hyperlink View action for a particular record*@
                        
                        <a href="DeleteUniversity/@item.ID">Delete</a> | @*Generate a hyperlink Delete action for a particular record*@    
                    </td>
                </tr>
            }
        </table>
    </div>
</body>
</html>

Step 29 :

When we click on the Hyperlink we have to fetch the data on a new page to have the confirmation for Deleting the record. So will create a new page named as “DeleteUniversity.cshtml” . All the html files will be inside the View Directory of University Folder. Then only the University Controller can access those Views.

@model MyApp.Models.University

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>DeleteUniversity</title>
</head>
<body>
    
        <div>
            <h4>University</h4>
            <hr />
            <h4><font color="red"> Are You Sure You Want to Delete this Record? </font></h4>
            <b>Reg No -></b>
            @Model.RegNo <br />   @*Fetching the Reg No from the record*@
            <b>University Name -></b>
            @Model.Name <br />  @*Fetching the Name from the record*@
            <b>University City -></b>
            @Model.City <br /> @*Fetching the City from the record*@
        </div>
        <p>
            <a href="/University/Index">No</a> | @*Generating a Link to Hit the Index Page*@
            <a href="/University/DeleteUniversityConfirm/@Model.ID">Yes</a> @*To Hit the Action DeleteUniversityConfirm()*@  
            
        </p>

</body>
</html>

The above page will fetch the data from the Model Class University which is passed along with the DeleteUniversity().

When we will click on Yes it will invoke the DeleteUniversityConfirm() which will do the deletion of record and will redirect to the HomePage(Index.cshtml)

Step 30 :

Will add a Action method named “DeleteUniversity()” and “DeleteUniversityConfirm ()” in our UniversityController.cs

publicActionResultDeleteUniversity(int Id) // Passing the Primary Key of the record 
        {
UniversityDALudal = newUniversityDAL();  //Creating an object of DAL
University u = udal.Universities.Find(Id); //Using DAL Find() method to fetch the record
return View("DeleteUniversity", u); //Passing the Model to the DeleteUnviverty.cshtml Page
        }

publicActionResultDeleteUniversityConfirm(int Id) // Passing the Primary Key of the record for deletion
        {
UniversityDALudal = newUniversityDAL(); //Creating an object of DAL
University u = udal.Universities.Find(Id); //Using DAL Find() method to fectch the record
udal.Universities.Remove(u); //Using DAL Remove() to delete the record
udal.SaveChanges(); //Using DAL SaveChanges() to update our Database
returnRedirectToAction("Index"); //Returning to our Index page after changes are saved
        }

Step 31:

Lets rebuild the project and execute it.

To make sure we have new data in database you can delete the previous records using DROP command.

Add some new records to the Database. (I have added two new records)

We can see that a View and Delete hyperlink is generated.

As soon as we click the Delete for a record it hits the DeleteUniversity() method and invokes the DeleteUniversity.cshtml page with its records.

The below is a view for the first record with a No link to hit the Index Page and Yes link to delete the record via invoking DeleteUniversityConfirm().

Lets click on “Yes” and observe the change below :

We can see that the first record is deleted and the Index page is shown with the updated Database using DAL layer.

UPDATE METHOD :

In Update Method the aim is to update the record of a particular student. So here I am making an approach for creating a unique hyperlink for Upadte using basic tags. So every record you insert will have its unique hyperlink for updation. And that hyperlink will pass that particular record to the Action Controller and will return the view after the updation.

Step 32 :

So now we need to make some changes in Index.cshtml file that will generate a hyperlink for the new record for Updating.

@using MyApp.Models
@model List<University>
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div> 
        <h1><a href="Create"> Add  a New University </a></h1> <br />
        <table border="1">
            <tr>
                <th>Reg No</th>
                <th>University Name</th>
                <th>University City</th>
            </tr>
            @foreach (University item in Model)
            {
                <tr>
                    <td>@item.RegNo</td>
                    <td> @item.Name </td>
                    <td> @item.City </td>
                    <td> <a href="ViewUniversity/@item.ID">View</a> | @*Generate a hyperlink View action for a particular record*@
                        <a href="DeleteUniversity/@item.ID">Delete</a> | @*Generate a hyperlink Delete action for a particular record*@ 
                        <a href="EditUniversity/@item.ID">Edit</a> | @*Generate a hyperlink Edit action for a particular record*@  
                    </td>
                </tr>
            }
        </table>
    </div>
</body>
</html>

Step 33 :

When we click on the Hyperlink we have to fetch the data on a new page. So will create a new page named as “EditUniversity.cshtml” . All the html files will be inside the View Directory of University Folder. Then only the University Controller can access those Views.

@model MyApp.Models.University
@{
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>EditUniversity</title>
</head>
<body>
    <div>
        <h4>University</h4>
        <hr />
        <form name="frm" action="/University/EditUniversityUpdate/@Model.ID" method="post"> @*Invoking Action*@
            <label>Reg No</label>
            <input type="text" name="RegNo" value="@Model.RegNo"><br /><br /> @*Populating the value in TextBox*@
            <label>University Name</label>
            <input type="text" name="Name" value="@Model.Name"><br /><br /> @*Populating the value in TextBox*@
            <label> University City</label>
            <input type="text" name="City" value="@Model.City"><br /><br /> @*Populating the value in TextBox*@
            <input type="submit" value="Update" />
            <p>
                <a href="/University/Index">Home Page</a>  @*Link to Index Page*@
               
            </p>

        </form> 
    </div>
</body>
</html>

The above page will fetch the data from the Model Class University which is passed along with the EditUniversity() Method.

When we will click on Update it will invoke the EditUniversityUpdate() which will do the updation of record and will redirect to the HomePage(Index.cshtml)

Step 34 :

We have added the hyperlink for the Edit, we have also created a page for that view. Next is to fetch the record using the Action Method and passing it to the EditUniversity.cshtml.

Will add a Action method named “EditUniversity()” and “EditUniversityUpdate()” in our UniversityController.cs

publicActionResultEditUniversity(int Id) // Passing the Primary Key of the record
        {
UniversityDALudal = newUniversityDAL(); //Creating an object of DAL
University u = udal.Universities.Find(Id); //Using DAL Find() method to fectch the record

return View("EditUniversity", u); //Passing the Model to the EditUnviverty.cshtml Page
        }


[HttpPost]
publicActionResultEditUniversityUpdate(University u) 
        {
if (ModelState.IsValid) {   // Checking Validations
UniversityDALudal = newUniversityDAL();  //Creating an object of DAL
udal.Entry(u).State = System.Data.Entity.EntityState.Modified; //Using DAL function to edit the record
udal.SaveChanges(); //Using DAL SaveChanges() to update our Database
returnRedirectToAction("Index"); //Returning to our Index page after changes are saved
            }
returnRedirectToAction("Index");

        }

Step 35 :

Lets rebuild the project and execute it.

To make sure we have new data in database you can delete the previous records using DROP command.

Add some new records to the Database. (I have added two new records)

We can see that a View ,Deleteand Edit hyperlink is generated.

As soon as we click the Edit for a record it hits the EditUniversity() method and invokes the EditUniversity.cshtml page with its records.

The below is a view for the first record with a HomePage link to hit the Index Page and Update button of type submit to update the record via invoking EditUniversityUpdate().

Step 36 :

Lets Edit some fields and observe the change below :

We can see that the first record is updated and the Index page is shown with the updated Database using DAL layer.

Conclusion :

In the previous and this article I have tried my best to implement CRUD operation using Entity Framework along with a simple form and database connectivity. I hope this article have been really knowledgeable to you and will help you out to understand the basic operation using EF.

Thank You for your support..!

Recommendation
Read Custom authentication filter in ASP.NET MVC after this article.
Page copy protected against web site content infringement by Copyscape

About the Author

Panthmadan
Full Name: Madan Panth
Member Level: Starter
Member Status: Member,MVP
Member Since: 12/15/2015 4:34:44 AM
Country: India

www.questpond.com
Learn MVC in 16 hours
Learn design pattern in 8 hours
Learn C# in 100 hours series
Learn MSBI in 32 hours
Learn SharePoint Step by Step in 8 hours

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)