Friday, June 4, 2021

MVC Transfer data from model to controller and vice-versa

In this post, we will see how we can send data from model to controller and vice versa.

Example: First of all, we do the following steps.
  • Create model class named Student in Models folder. Models/Student.cs file
  • Create Home controller in Controllers folder. Controllers/HomeController.cs file
  • Create Index action method in Home controller.
  • Create Index view. Inside Views/Home folder. Views/Home/Index.cshtml file
Step1. Create a class named Student in Models folder.
namespace WebMVC.Models
        {
           public class Student
            {
                public int Id { get; set; }
                public string Name { get; set; }
                public int Age { get; set; }
            }
        }

Step2. Create a Home controller in Controllers folder. The Index action method in Home controller is created automatically.
  using System.Web.Mvc;

    namespace WebMVC.Controllers
    {
        public class HomeController : Controller
        {
        // GET: Home
            public ActionResult Index()
            {
            return View();
            }
        }
    }

Step3. Create Index view.

Now, we have the following alternatives:
  • First, the data can be accessed from database or 
  • Second, the data can be created inside model class Student or 
  • Third, the data can be created inside Home controller as well. 
Entity Framework Code first approach: To get data from database, we must have a Student table having the same properties as specified in the Student class. The name of the table may or may not be the same but the fields of the table must match the properties of the Student class. In other words, the schema of the table should match with the class. Since getting data from database requires connection and provider etc. which is slightly more difficult concept to learn in first attempt. So, we consider the third possibility and create student data inside the Index method of Home controller and pass it as argument to View(). It is explained below. 

Send a Student data from Controller to View

We see the updated codes below.
File name: HomeController.cs

using System.Web.Mvc;
using WebMVC.Models;

namespace WebMVC.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            Student s1 = new Student() { Id = 1, Name = "Ajay", Age = 22 };
            return View(s1); //Note the parameter
        }
    }
}
File name: Index.cshtml

@model WebMVC.Models.Student

@Html.TextBoxFor(model => model.Id)
<br />
@Html.TextBoxFor(model => model.Name)
<br />
@Html.TextBoxFor(model => model.Age)
<br />

Build the project by pressing CTRL+SHIFT+B, we have the following folder file  structure in Solution Explorer.



OUTPUT

Send a list of students data from Controller to view

Next we see how to send a list of students to view. We see the updated codes below.
File name: HomeController.cs

using System.Collections.Generic;
using System.Web.Mvc;
using WebMVC.Models;

namespace WebMVC.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            Student s1 = new Student() { Id = 1, Name = "Ajay", Age = 22 };
            Student s2 = new Student() { Id = 2, Name = "Ayub", Age = 21 };
            Student s3 = new Student() { Id = 3, Name = "Jay", Age = 17 };
            List students = new List();
            students.Add(s1);
            students.Add(s2);
            students.Add(s3);
            return View(students); //Note the parameter
        }
    }
}

File name: Index.cshtml

@model IEnumerable<WebMVC.Models.Student>
<table>
    @foreach (var student in Model)
    {
        <tr>
            <td> @student.Id </td>
            <td> @student.Name </td>
            <td> @student.Age</td>
        </tr>
    }
</table>

OUTPUT
NOTE we can use List<WebMVC.Models.Student> instead of IEnumerable<WebMVC.Models.Student>
See the below modified code. It will result the same output.
File name: Index.cshtml

@model List<WebMVC.Models.Student>
<table>
    @foreach (var student in Model.ToList())
    {
        <tr>
            <td> @student.Id </td>
            <td> @student.Name </td>
            <td> @student.Age</td>
        </tr>
    }
</table>
OUTPUT


What we learnt?

  1. To get model class data into controller, we use the namespace. For example, using WebMVC.Models; in controller class file.
  2. We create instance of the model class and pass it as argument to the View() which returns view in action method so that data is transferred from controller to view.
  3. We use @model directive in view page to refer the model class so as to bind the model class data/properties with the view HTML strongly typed controls. For example, @model WebMVC.Models.Student or IEnumerable<WebMVC.Models.Student> or @model List<WebMVC.Models.Student>
  4. If data passed into View() is enumerable type such as List, we use @model IEnumerable<WebMVC.Models.Student> or @model List<WebMVC.Models.Student> in the view page. foreach loop is used to access such data.

No comments:

Post a Comment

Hot Topics