Article

Passing Data to view from Controller in ASP.NET Core MVC

In this article we will learn How to Passing Data to view from Controller in ASP.NET Core MVC.

In this blog we will see how to passing data to view from Controller in ASP.NET Core MVC ?

Project Structure

Multiple way available to pass data from a controller to a view

i. Using ViewData
ii. Using ViewBag
iii. Using a strongly typed model object. This is also called Strongly typed view.

In this blog we will pass data using ViewData from a controller to a view.

We will create one folder with Models name after that we will add two classes in this folder with name Student.cs and MockStudentRepository.cs and one interface with name IStudentRepository.cs.

Write this code on Student.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Demo.Models
{
    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
    }
}

Write this code on IStudentRepository.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Demo.Models
{
    public interface IStudentRepository
    {
        Student GetDemoData(int id);
    }
}

Write this code on MockStudentRepository.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Demo.Models
{
    public class MockStudentRepository : IStudentRepository
    {
        private List<Student> _studentList;
        public MockStudentRepository()
        {
            _studentList = new List<Student>()
            {
                new Student(){Id=1, Name="Manish",Email="Manish@gmail.com" },
                new Student(){Id=2,Name="Rajesh",Email="Rajesj@gmail.com"}
            };
        }
        public Student GetDemoData(int id)
        {
            return _studentList.FirstOrDefault(e => e.Id == id);
        }
    }
}

Then we will open startup.cs page and write this code in ConfigureServices method and Configure method.

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddSingleton<IStudentRepository, MockStudentRepository>();
           
        }

 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseMvcWithDefaultRoute();
            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello World!");
            });
        }

After that we will create one folder with name Controllers then will add controller class with name “HomeController.cs”.

Code for HomeController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Demo.Models;
using Microsoft.AspNetCore.Mvc;



namespace Demo.Controllers
{
    public class HomeController : Controller
    {
        private readonly IStudentRepository _studentRepository;

        public HomeController(IStudentRepository studentRepository)
        {
            _studentRepository = studentRepository;
        }
        public ViewResult Details()
        {
            Student model = _studentRepository.GetDemoData(1);
            ViewData["Student"] = model;
             return View();
        }
    }
}

We will create One Views folder then in views folder create sub-folder with name “Home” then finally we will add one Razor View page in Home folder with name keep “Details.cshtml”.

We will open Details.cshtml and write this code.

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    @{
        var student = ViewData["Student"] as Demo.Models.Student;
    }
    <h3>Name :@student.Name</h3>
    <h3>Email :@student.Email</h3>
</body>
</html>

Output

Leave a Reply

Your email address will not be published. Required fields are marked *