As.Net core tutorials

Updated : Apr 27, 2020 in Articles

How to pass data controller to view in asp.net core

in this lesson we will see how to pass data controller to view in asp.net core this is similar to MVC Framework

Asp.net core and MVC both we are using viewBag, Viewdata, TempData passing data from controller to view

previous MVC Framework (Model, view, controller) how we can pass the same way here also we can pass the data to a controller to view.

In the Visual Studio 2019, create new ASP.NET Core Web Application project

Select Empty Template and Click Ok button to Finish

Add Configurations: 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 ControllerToView
{
    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 Controller: Create a new folder named Controllers. In this folder, create a 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 ControllerToView.Controllers
{
    public class DemoController : Controller
    {
        public IActionResult Index()
        {
            ViewBag.age = 30;
            ViewBag.FullName = "Vijay";
            ViewBag.price = 5.5;
            ViewBag.TodayDate = DateTime.Now;
            return View();
        }
    }
}

Create View: Create a new folder name like  Views. In this folder, create a new folder named Demo. Create a new 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 />
    Price: @ViewBag.price
    <br />
    Birthday: @ViewBag.TodayDate.ToString("MM/dd/yyyy")

</body>
</html>

Structure of ASP.NET MVC Core Project

Run Application: Access Index page  action in Demo controller with the following URL:  http://localhost:56985/Demo/Index

Like
Like Love Haha Wow Sad Angry