Tech Junkie Blog - Real World Tutorials, Happy Coding!: Hour 4: ASP.NET Core : Create Our First Controller and View

Friday, July 26, 2019

Hour 4: ASP.NET Core : Create Our First Controller and View

In the previous post we have enabled MVC on our application.  Now we want to add our first MVC controller and view to test out verify that MVC is working.  We also have to tell ASP.NET Core what pattern to look for when looking for our controllers and views.




Step-By-Step Instructions:

1.  Add a folder call "Controllers" in the root of your application



2. Right click on the "Controllers" folder and select "Add" → "New Item" → .NET Core → MVC Contoller - Empty, then click "Add"



Type HomeController when prompted









3.  You see the "HomeController.cs" class being added to the "Controllers" folder



4.  Double click on the "HomeController.cs" file and you will see the following code

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

namespace NorthwindCafe.Web.Controllers
{
    public class HomeController : Controller
    {
        // GET: //
        public IActionResult Index()
        {
            return View();
        }
    }
}

5.  Create a folder in the root of the application call "Views" then inside the "Views" folder create another folder call "Home".  MVC is a framework that works best when you follow the convention, by creating the folders in this hierarchy MVC knows where to look and does the plumbing for you.  If you notice the home folder matches the controller name of the HomeController.  With routing you can deviate from this convention, but it takes more work.

6.  Right click on the "Home" folder and select Add → New Item → ASP.NET Core → Razor View, keep the name of the view as Index.cshtml then click "Add"



























7 .  Double click on the view "Index.cshtml" and type "Hello World" between the <div> tag like the markup below

@{
    Layout = null;
}

<!DOCTYPE html>

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


9.  To enable routing for our application, so that MVC knows how to find our view, open up the Startup.cs file and modify the app.UseMvc() method's config instance to configure the routes for our application

        public void Configure(IApplicationBuilder app)
        {
            app.UseStaticFiles();
            app.UseMvc(config => {
                config.MapRoute(
                    name: "Default",
                    template: "{controller}/{action}/{id?}",
                    defaults: new  { controller = "Home", action = "Index" }
                    );
            });
        }

The code above configures the default route for our application with name of the route assigned to "Default", the "template:" field specifies the pattern that MVC should look for when locating our routes.  The "defaults:" field uses an anonymous object to define a default route in case nothing is found or nothing is typed into the URL.

10. Add the line services.AddMvc(); to the ConfigureServices method like so:


        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }

The above code uses dependency injection to inject MVC into the application, whenever it is needed. 11.  Now when you press Ctrl+5 you will see our "Hello World"












If you encounter the following error: You forgot to add the line services.AddMvc(); to the ConfigureServices method.

github Repository:  https://github.com/techjunkiejh/NorthwindCafe/tree/Hour4

Previous: Hour 3: Enable MVC On ASP.NET Core Application

7 comments:

  1. If you are searching for professional Office cleaning in Perth, you are at the right place. We are providing the Best House Cleaning Services in Perth. Our team provides the very best cleaning solutions, all at fantastic prices. Visit our website to learn more!

    ReplyDelete
  2. If you’re looking cleaning services in Perth, then End of Lease Cleaning Service in Perth is the answer. End of Lease Cleaning Perth offer fixed priced bond cleans and end of lease cleaning services. We offer professional End of lease cleaners in Perth.

    ReplyDelete
  3. Online PDF to Word converter free to convert documents online, Upload your file and transform it into Word in one click. Convert your Doc and Docx right now into Word and PDF format. Visit our Website!

    ReplyDelete
  4. App Dev Zone providing you many leading services, one way For All Design, to meet the marketing needs and Development. Including Logo Design, SEO services (SEO booster), WordPress Website Design and Hosting in all over World. Visit our Website to learn more!

    ReplyDelete
  5. HH Floor Sanding Perth provides all floor sanding services including restoration, staining, finishing and repair services, in all other Suburbs of Western Australia. We are a professional floor sanding company. Call 0411 151 555 for dust-free floor sanding services.

    ReplyDelete
  6. Baltic Legitimate centers on Corporate Law, Assess Law, Company Arrangement and Enrollment, and Bookkeeping Administrations in all three Baltic states - Estonia, Latvia and Lithuania. In case you proposed to begin trade within the Baltic States, our group of experts will give you with full back and exhortation in choosing the sort of a company, building up and enlistment of the company, managing with assess issues, and advancing your trade in Latvia, Lithuania or Estonia. https://www.baltic-legal.com/

    ReplyDelete

Search This Blog