MVC - C# -Creating a Student model, Populating in StudentController and passing it to View

  • Create Student model (Student)

       
Student.cs
namespace MvcVersionFinder.Models
{
    public class Student
    {
        public string Name {get;set; }
        public int Age { get; set; }
        public double GPA { get; set; }
        public int YearinGraduation{get; set;}
        public int Trade { get; set; }
       
    }
}


  • Create Student controller

StudentController.cs
using MvcVersionFinder.Models;
namespace MvcVersionFinder.Controllers
{
    public class StudentController : Controller
    {
        //
        // GET: /Student/
        public ActionResult Index()
        {
            Student student = new Student();
            student.Name = "Abe Lincoln";
            student.Age = 19;
            student.YearinGraduation = 2;
            student.GPA = 3.8;
            return View(student);
        }
    }
}

  • Create view from Index function of Student controller

index.cshtml
@model MvcVersionFinder.Models.Student
@{
    ViewBag.Title = "Index";
}
<div style="font-family: Arial; color: blue">
        <li>Name: @Model.Name</li>
        <li>Year in Graduation: @Model.YearinGraduation</li>
        <li>Age: @Model.Age</li>
        <li>Trade: @Model.Trade</li>
        <li>GAP: @Model.GPA</li>
    </div>   


  • Output

http://localhost:81/MvcVersionFinder/student

       Index
•Name: Abe Lincoln
•Year in Graduation: 2
•Age: 19
•Trade: 0
•GAP: 3.8

No comments:

Post a Comment