ASP.NET Core 6.0 MVC Tutorial Day 2

ASP.NET Core 6.0 MVC Tutorial Day 2

Learning Objective: Let’s start with ASP.NET Core 2.0 MVC Fundamental Concepts like Controller and View.

You need Visual Studio 2022

As you are developer you can download Visual studio 2022 Community Edition Free of Cost.

Hope you have gone through with C# and HTML Fundamental. Let’s begin with ASP.NET Core 2.0 MVC Development using Visual Studio 2022.


Start Visual Studio 2022 (Run: devenv )

File > New > ASP.NET Core Web App (Model-View-Controller)

Press Next

Select Framework 6.0

Authentication Type: None

Configure for HTTPS : Yes

Create

Your Web Project is ready with all the basic structure. Now its time to run and test basic/sample project.

Press F5 (Start Debugging) or Ctrl+ F5 (Start without Debugging)

Your project will start on localhost with some port number like:

https://localhost:7054/



Your default controller code will be as follow:

using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using WebApplication1.Models;

namespace WebApplication1.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {
            return View();
        }

       

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}

Above Code says that you have 2 Menu Options. Index and Privacy, Now check out the view folder in Solution Explorer

Now I would like to add one more menu options like About so I have added new View (Right Click on Views > Home Folder and select Razor View > Give name as About.

Add About Code block into HomeController and Last to add into menu options you need to update _Layout.cshtml file.

   public IActionResult About()
        {
            return View();
        }

If you don’t want to use default layout then you can set layout = null using Razor Syntax.

@{
        Layout = null;
}

<div class="text-center">
    <h1 class="display-4">About Us</h1>
</div>

If you don’t want to create view and want to return just string when someone calls this url, you can use following code:

public String Terms()
        {
            return "This is Terms and Conditions";
        }

By Default it will search for the View with the same name as method name, If you have create view with different name then you need to pass as parameters.

 public IActionResult About()
        {
            return View("AboutUs");
        }