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

Monday, July 18, 2016

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 Class, then click "Add"




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"

6.  Right click on the "Home" folder and select Add → New Item → .NET Core → MVC View Page, 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>

8. Press Ctrl+F5 to run the application, you will see the following.



9.  All you will see is an empty page, where is our "Hello World"?  The reason we don't see our view is because we haven't define any routes for our application yet.

10.  To enable routing for our application 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.

11.  Now when you press Ctrl+5 you will see our "Hello World"












If you encounter the following error:
System.InvalidOperationException
Unable to find the required services. Please add all the required services by calling 'IServiceCollection.AddMvc' inside the call to 'ConfigureServices(...)' in the application startup code.
C:\NorthwindCafe\NorthwindCafe.Web\Startup.cs
Line 17: {
Line 18: app.UseStaticFiles();
Line 19: app.UseMvc(config => {
Line 20: config.MapRoute(
Line 21: name: "Default",
at Microsoft.AspNetCore.Builder.MvcApplicationBuilderExtensions.UseMvc(IApplicationBuilder app, Action<IRouteBuilder> configureRoutes)

at NorthwindCafe.Web.Startup.Configure(IApplicationBuilder app) in C:\Users\Jason\Source\Repos\Grades\NorthwindCafe\NorthwindCafe.Web\Startup.cs:line 19
System.Reflection.TargetInvocationException
Exception has been thrown by the target of an invocation.
at System.RuntimeMethodHandle.InvokeMethod(object target, Object[] arguments, Signature sig, bool constructor)

at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(object obj, Object[] parameters, Object[] arguments)

at System.Reflection.RuntimeMethodInfo.Invoke(object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)

at Microsoft.AspNetCore.Hosting.Internal.ConfigureBuilder.Invoke(object instance, IApplicationBuilder builder)

at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()


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





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



ASP.NET Core Posts:
  1. How To Create An ASP.NET Core Application From Scratch
  2. ASP.NET Core : Add jQuery, Bootstrap, AngularJS Using bower.json
  3. Enable ASP.NET Core to Serve Static Files
  4. Enable MVC On ASP.NET Core Application
  5. ASP.NET Core : Create Our First Controller and View  
  6. ASP.NET Core : Adding The Default View With _ViewStart.cshtml
  7. ASP.NET Core : Create A Responsive Layout With Bootstrap
  8. ASP.NET Core : Adding Font-Awesome For Northwind Cafe Navigation Icons
  9. ASP.NET Core : Add .json Configuration Files With Microsoft.Extensions.Configuration Library
  10. ASP.NET Core : Entity Framework Core Models For Northwind Cafe
  11. ASP.NET Core : Create The NothwindContext ( EntityFrameworkCore )
  12. ASP.NET Core : Configure project.json File To Support Entity Framework Core
  13. ASP.NET Core : Add NorthwindContext To Startup Class And Create Database
  14. ASP.NET Core: Seeding The NorwindCafe Database
  15. ASP.NET Core: Add Logging To The NorthwindCafe Application

1 comment:

Search This Blog