Pass Data from Controller to View in ASP.NET Core MVC


On the Visual Studio, create new ASP.NET Core MVC Web Application project

Select Empty Template

Click Ok button to Finish




Open Startup.cs file and add new configurations as below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace LearnASPNETCoreMVCWithRealApps
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Demo}/{action=Index}/{id?}");
            });

        }
    }
}

Create new folder named Controllers. In this folder, create new controller named DemoController.cs as below:

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

namespace LearnASPNETCoreMVCWithRealApps.Controllers
{
    public class DemoController : Controller
    {
        public IActionResult Index()
        {
            ViewBag.age = 20;
            ViewBag.fullName = "Kevin";
            ViewBag.status = true;
            ViewBag.price = 4.5;
            ViewBag.birthday = DateTime.Now;
            return View();
        }
    }
}




Create new folder named Views. In this folder, create new folder named Demo. Create new razor view named Index.cshtml as below:

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>

    Age: @ViewBag.age
    <br />
    Full Name: @ViewBag.fullName
    <br />
    Status: @ViewBag.status
    <br />
    Price: @ViewBag.price
    <br />
    Birthday: @ViewBag.birthday.ToString("MM/dd/yyyy")

</body>
</html>




Access Index action in Demo controller with following url: http://localhost:48982/Demo/Index

Output

I recommend you refer to the books below to learn more about the knowledge in this article: