DEV Community

Cover image for ASP.NET Core Blog tutorial: MVC
Dayvster 🌊
Dayvster 🌊

Posted on • Edited on • Originally published at arctek.dev

ASP.NET Core Blog tutorial: MVC

Welcome Back!

Glad you decided to stick around and learn more. Don't worry I'm not gonna bore you with a long story this time. No no, this time we'll get straight to the good part from the get go.

So what we'll be covering in this part of the series is the MVC pattern. You've already taken your first step towards implementing a MVC pattern by creating the Model.cs base class and the Post.cs model class. Now we'll take the next step and create the C part of MVC.

The Controller

But Dave what happened to the V, where's the V man!?

Don't worry about it, none of your business, the V's fine. Forget about it for now. The controller stands between the model and the view, it receives a request takes a view and fills it with the data it gathers from the model. Sorta like a bartender pouring you a cocktail. Regardless, I firmly believe in learning by doing so let's create our first controller.

What you're want do is right click that controllers folder we set up in the previous example and create a new file called HomeController.cs.

using System;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Mvc;

namespace Blog.Controllers{
    // the slash means that this will be the default controller
    // Basically if the URL does not provide any additional routes 
    // this controller will be called.
    [Route("/")]

    // the standard practice is to name your controllers
    // HomeController or PostController or UserController
    // Either way just make sure they end with Controller
    // or don't... your business really
    // but it does make it a lot easier since ASP.NET does some magic...that we'll show later
    public class HomeController : Controller{

        // the default action called is index and takes no parameters
        public IActionResult Index(){
            return Content("Home controller called!");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

But wait there's more! Find and open up a class named Startup.cs and change it to look like this:

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;
using Microsoft.Extensions.Hosting;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Mvc;

namespace Part_one{
    public class Startup{
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services){
            services.AddMvc(o => {
                o.EnableEndpointRouting = false;
            });

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env){
            if (env.IsDevelopment()){
                app.UseDeveloperExceptionPage();
            }
            app.UseStaticFiles();
            app.UseMvc(routes => {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

Don't worry about any of this, plenty of time to learn the ins and outs of configuration and boilerplating. Now re-launch your application, open up http://localhost:5000 and just like that you should see.

Home controller called!
HE HEY! It works, pretty cool right? But at the same time pretty boring, I mean it's just a string of text, nobody is gonna pay you millions of dollars to visit this website, no matter how amazing your writing skills may be.

The View

No, not the TV show! When it comes to ASP.NET Views are basically template files that will later get filled with data from the appropriate model or models by the controller. Look let's just create one to make you understand what I mean

Create two more folders in your Views folder named Shared and Home. Now right click that Shared folder and create a file named _layout.cshtml.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Super Awesome Blog </title>
</head>
<body>
    <section class="main-content">
        @RenderBody()
    </section>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Pretty much your standard HTML file right there, except for that @RenderBody(), that right there is a razor template function that tells us where the body or the main contents of the layout should be filled in.

You'll get it in a moment...

Now right click that Home folder and create a new file called Index.cshtml

@{
    //
    Layout = "~/Views/Shared/_Layout.cshtml";
}
@{
    // Anything in between these two curly braces will be handled by 
    // the razor templating engine
    // basically you can put almost any C# code in here and expect it to work
    // Observe

    string test = "Test";
    string test2 = "123";
    string newString = String.Format("{0} {1}", test, test2);

    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>Dave, I'm home!!</h1>
<h2>@newString</h2>
<p>
    Lorem, ipsum dolor sit amet consectetur adipisicing elit.
    Optio voluptatibus illo eligendi nesciunt dolor sunt rem 
    suscipit, quo, nemo recusandae earum impedit magni 
    mollitia quod omnis nulla voluptatum. Quisquam, quis.
</p>
Enter fullscreen mode Exit fullscreen mode

Not much to see right there and if you have some prior html knowledge you may be confused as to... where the rest of it is. Don't worry about it.
Now let's go back to our HomeController.cs and change the return Content("Hello...") to

using System;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Mvc;

namespace Blog.Controllers{
    [Route("/")]
    public class HomeController : Controller{
        public IActionResult Index(){
            return View();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

ASP.NET will automatically look for the Views folder and a folder named the same as the controller in there, so in this case Home and then it will automatically look for an Index.cshtml file in there to display as our View.

If we relaunch our application we should now see the contents of the Home/Index.cshtml View and if we inspect our webpage we can see that it is indeed using the layout we specified in _layout.cshtml.

This is great news but it's not yet a complete MVC it's more of a VC. In our next tutorial we'll create a database, fill it with example data and see if we can't display some posts on our webpage and complete the MVC.

If you have any questions or remarks feel free to contact me on twitter @Arctekdev

Top comments (0)