Wednesday, May 27, 2015

Building a Blog - Controller and First Preview of the Blog

We have created Model and Data Access Layer classes in previous posts. Now it is time to create a Controller and see the first View of our Blog.

If you are in this post for the first time I suggest you go to the very first post of this small project for Building a Blog and see what is this all about. You can check it HERE.

Assuming you have the Models and Data Access Layer classes created, you should go to your Controllers folder and add a new Controller. We want to read the data from the database that will be created upon the start of our application and then present that data on the web browser trough the View that we will make. So...

1. Add a new Controller by right-clicking the Controllers folder and then Add, then Controller.

2. On the Add a Scaffold window, choose MVC 5 - Empty

3. Give it a name "PostsController".

You should have your Controllers folder now having one controller like this:

ASP.NET Controller


And your class should look like this:

Empty Controller Class
As you can notice this class we created inherits Controller class, to have the functionalities of the Controller.

What we need to do now is, as we did with the Model creation process, specify to use few class packages. So below using System.Web.Mvc;  we have to again say to this class use Entity Framework package. We add:

- using System.Data;
- using System.Data.Entity;

Then we also need to tell this class that it will use our Models folder or the namespace which our Models are under so that we can access to them as our Context class is under the Models namespace even though it is in a different folder because we changed the namespace in that folder for the Context class:

-  using BlogProject_Dusan_MVC.Models;

Now what we need to set first for this class is to have one instance of our Database Context Class. So right inside  of the class (public class PostController: Controller) you add one private property so that is only accessible to this class like this:

- private BlogContext db = new BlogContext();

Now we need to create a method for our Controller class that will get the data from our database. We make a method like this:

public ActionResult Index()
{

}

ActionResult is the class from an MVC package of classes and we call it Index because it is the most common way to call the first page method for the classes. However, this method will show warning on the Index() because you are not returning any value when using the ActionResult class.

So the next thing we have to write is to read the posts for the blog from the database using Linq and Entity. Inside the Index() method we write:

- var posts = db.Posts.Includep => p.Blog);
return View(posts.ToList());

What we basically did is we set one variable that reads our BlogContext class, and from it Posts table that are connected to the Blog table.

Then we return the value of that variable in a List to the View, that we have to create in order to see what is being listed out. But first, the class you have just created it should look like this:

Controller Class with ActionResult method


If this is how your class look like that is good. But let's make one change in our App_Start folder, then RouteConfig class.

Change the controller="Home" to controller="Posts". What this class is doing is simply set to read our Controller upon the start of the application.

Now do one build of your application. You can do this by either pressing Ctrl+Shift+B or go to Build then choose Build solution.

If no error is shown in the Output Window of Visual Studio it means your code is written out properly. If you do have, you should re-check what you have written and fix the errors that are shown.

Then start an application by either pressing Ctrl+F5 or go to Debug Start Without Debugging. Your application should start and you should get something like this:

ASP.NET MVC View Missing Error

This means that your View cannot be found. Because in the method you have made, you said to return the data to the View but there is no View made that it should use. So go back to your PostsController and right click on the Index() of the method and choose Add View.

View name should be Index, to match the name of the method in the Controller and Template should be Empty.

Once you do that, you will get in the Views folder of your Visual Studio application another folder that is called as your controller is. And inside of that folder a View called Index.cshtml.

If you start your application again, you should see an empty blank web page with the name of your View. Like this:

ASP.NET MVC Empty View Page

So now we should write in our View some code to read the data from our database properly. So go to the view you have Added and open it up.

There should be ViewBag.Title = "Index" you can change this to "Posts" as that is changing the <title></title> tag in the Shared layout page.

And then you have <h2>Index</h2> and you can change this to Posts too, as that is what is being written out on the page. The @{} you see, it is the Razor technology to read some of the C# functions on the page.

But what you need to do is to specify on the very top of the Index.cshtml file, the very first, number 1 line, you need to write this:

@model IEnumerable<BlogProject_Dusan_MVC.Models.Post>

This is saying that this page is using strongly-typed View for the model that is being stored as List, because you said in the method of Controller you are returning a List, and we write IEnumberable as there is a collection of object we need to read.

After the <h2></h2> tag we have to use foreach with Razor to read trough all the elements from the database table EntityFramwork created for us. Like on the next picture:

Index.cshtml page to read data from database.


What is this doing is, for each item in the Model, which in our case it is Post model, display the Title and the Content of our Posts. The <table> is there just to show the items from database in proper order and to look more "user friendly".

So now if you start your application, you should get something like this:

Blog posts read from Database

I know it is just dull 1 2 3 4 numbers and same text, but this is how the posts usually look at the Blogs. You have the title and the content of the post. What next we should do is to create a View where we can Create new posts. But for now...

That is it! However, it is WAY FAR from being perfect or to even call it a proper blog. My goal was to show that you can start with something simple and small and build on that, but also introduce you to some ASP.NET MVC stuff. Now we have a page that reads the Posts and presents them to the user.

There is like tons of other things we can do and well... We must do if we want to have a proper blog. Like first thing that comes to my mind now is, to alter our database tables to have DateTime fields so that we track when the post is being created. Then our Posts need to have a shorter description to give the user some info about what he can read in the post. But then there arises a problem of having the views for the description and the View of that post.

What else... Yeah, we have to have a logging system as well, because what if you want to have couple of Authors for one Blog? Then you have to store somewhere users who are Authors, which means creating another Database table and connecting it with the Blog table so that they match and who has the rights for which Blog to write upon.

Then commenting system as well. Where we need to have a table for Comments. It is like a lot you can do. One of the things is also using Bootstrap to get nice and responsive design. Then I can already see we would have to use Authorizations for the users and...you would say "OMG!! Who is going to do that!?No way! I am off" But...you shouldn't think of it as a lot things to do and I can't do it, but rather think of the challenges you put yourself into and the more you get over each challenge you get that much better. You understand more how things work and you become a great developer.

As for me, I will have to continue working on some applications I need to improve and see how far I can go. If i get time to continue on this Blog creation I will do so and continue writing, if not I will write of the applications I am currently working on.

I sincerely hope that this small series of MVC ASP.NET will be of use to beginners in MVC or anyone who is new to programming as I had need to write something more simple than what I usually do, because I wished sometimes someone had done it for me. If this helps you out, I will be happy.

Till next time, stay tall and keep your head high!