Tuesday 19 June 2018

CRUD Operations in MVC Part-1

In this tutorial we'll learn how to perform simple CRUD operations in MVC. This is the first part which will deal with a student model without database involvement. The second part of this tutorial will involve Entity Framework database with same operations and JQuery AJAX.

Read of CRUD

Step 1) Create new project in Visual Studio, select Visual C#, Select Web and then select ASP.NET Web Application, Name your project and then press OK button.



Step 2) Select MVC, change Authentication to "No Authentication" press OK and then OK


Step 3) Right click on your models, select add and then click class. A dialog will appear name the class i.e. "Student" and press Add


Structure of Student Class

public class Student
{
    public int Id { get; set; }
    public string First_Name { get; set; }
    public string Last_Name { get; set; }
    public DateTime Date_of_Birth { get; set; }
}

Structure of Project
Make sure you have all the folders and files within the folder which are highlighted with yellow color, all the folders are by-default added when we created the project, we have only added 1 student class nothing else. See the attached image.




Step 4) Open the HomeController.cs file, design your default page first, its called Index method within your HomeController.cs

List<Student> students = new List<Student>
{
    new Student{Id=1,First_Name = "John",Last_Name="Wick",Date_of_Birth= new DateTime(1988,6,12)},
    new Student{Id=2,First_Name = "Lisa",Last_Name="Joseph",Date_of_Birth= new DateTime(1989,5,21)},
    new Student{Id=3,First_Name = "Aman",Last_Name="Kaur",Date_of_Birth= new DateTime(1990,8,11)},
    new Student{Id=4,First_Name = "Ashish",Last_Name="Nehra",Date_of_Birth= new DateTime(1991,12,9)},
    new Student{Id=5,First_Name = "Kabeer",Last_Name="Khan",Date_of_Birth= new DateTime(1985,3,13)},
    new Student{Id=6,First_Name = "Satya",Last_Name="Narayan",Date_of_Birth= new DateTime(1990,6,5)},
    new Student{Id=7,First_Name = "Forman",Last_Name="Trump",Date_of_Birth= new DateTime(1998,01,6)},
    new Student{Id=8,First_Name = "Murad",Last_Name="Saeed",Date_of_Birth= new DateTime(1986,9,16)},
    new Student{Id=9,First_Name = "David",Last_Name="Rahul",Date_of_Birth= new DateTime(1999,05,26)},
    new Student{Id=10,First_Name = "Kinnerd",Last_Name="James",Date_of_Birth= new DateTime(1980,07,16)},
 
};
public ActionResult Index()
{
    //Pass List of Students to Index view page
    return View(students);
}

You'll have to add the reference to your student class within Controller code like this

using Blog.Models;

Step 5) Change your Index View page, go to your views, select Home, open file Index.cshtml and change the code with the below code

@model IEnumerable<Blog.Models.Student>
@{
    ViewBag.Title = "Home Page";
}
 
<h3>Students</h3>
<div class="row">
    <div class="col-md-4">
        <table class="table table-hover">
            <tr>
                <td><b>First Name</b></td>
                <td><b>Last Name</b></td>
                <td><b>Date of Birth</b></td>
            </tr>
            @foreach (var item in Model)
            {
                <tr>
                    <td>@item.First_Name</td>
                    <td>@item.Last_Name</td>
                    <td>@item.Date_of_Birth.ToString("dd/MM/yyyy")</td>
                </tr>
            }
        </table>
    </div>
</div>

Now run the project it will display the Index page like this:


Create of CRUD
Step 1) Create a new method within HomeController.cs like below

public ActionResult Create_New()
{
    return View();
}

Step 2) Right click on your Create_New( ) and create a new View like image below




ViewName; must be the same as your method name within your controller
Template: must be create, because we are creating a new record
Model Class: must be the Student class 
Now click on Add

Step 3) Add Create_New( ) Post method which will get the Student model from the view we've just created, don't forget to decorate other Create_New( ) method with [HttpGet]

[HttpPost]
public ActionResult Create_New(Student std)
{
    std.Id = students.Count() + 1;
    students.Add(std);
    return View("Index",students);
}

Step 4) Change your Index.cshtml and add link to the Create_New page like below

@model IEnumerable<Blog.Models.Student>
@{
    ViewBag.Title = "Home Page";
}
 
<h3>Students</h3>
@Html.ActionLink("Create new Student", "Create_New")
<div class="row">
    <div class="col-md-4">
        <table class="table table-hover">
            <tr>
                <td><b>First Name</b></td>
                <td><b>Last Name</b></td>
                <td><b>Date of Birth</b></td>
            </tr>
            @foreach (var item in Model)
            {
                <tr>
                    <td>@item.First_Name</td>
                    <td>@item.Last_Name</td>
                    <td>@item.Date_of_Birth.ToString("dd/MM/yyyy")</td>
                </tr>
            }
        </table>
    </div>
</div>

Step 5) Change your HomeController method Index with the below code

public ActionResult Index(List<Student> studentsList = null)
{
    if (studentsList == null)
        return View(students);
    else
        return View(studentsList);
}

Explanation: studentsList is the list we're passing from our Change_New( ) method, that is by-default set to null. Conditions check if passed is nothing or null then default list is displayed otherwise it will show the updated list of students, the above changes will change the Index page, create new page







Update of CRUD
Step 1) Create a new method within HomeController.cs like below

[HttpGet]
public ActionResult Edit(int Id)
{
    return View(students.Single(x => x.Id == Id));
}


Explanation: The above method gets the Id of the students and search it within list of students and return the desired record to Edit page


Step 2) Create a new view by right clicking on the Edit method just like we did in create method within HomeController.cs like below




Step 3) Copy and paste below method

[HttpPost]
public ActionResult Edit(Student std)
{
    var student = students.Single(x => x.Id == std.Id);
    student.First_Name = std.First_Name;
    student.Last_Name = std.Last_Name;
    student.Date_of_Birth = std.Date_of_Birth;
    return View("Index", students);
}

Explanation: The above method will get the student record and will update that instance within the list of students. Edit view page will also be same as the create new page, it will show the details of the student

Delete of CRUD
Step 1) Create a new method within HomeController.cs like below

public ActionResult Delete(int Id)
{
    var student = students.SingleOrDefault(x => x.Id == Id);
    if(student!=null)
        students.Remove(student);
    return View("Index", students);
}

That's it. The purpose of this tutorial was to provide you with basic understanding of how you can do basic operations in mvc using default template of MVC provided by Visual Studio.

Note: The above code doesn't work for multiple records i.e. edit, delete its because we are using in memory List not a database, the next tutorial will cover that issue, so you'll be able to permanently edit, delete, add new records effectively.

2 comments:

  1. Where is the view for Create_New??

    ReplyDelete
    Replies
    1. We just created view for Create_New by right-clicking on it, I didn't add the code because we didn't change anything in that code, it was the default generated code by the Visual Studio.

      Delete