ASP.NET on OpenShift part 5: Models in the MVC

Previous posts in this series:

Part 5 – Models

As we’ve been seeing in this series so far, MVC stands for Model-View-Controller. In the first two parts, I talked about the Controller. In the last two parts, we went over Views and putting your project on OpenShift. In this fifth and final part of the MVC series, I’m going to write about Models.

Models

Models are a way of passing data between the Controller and the View. In the last part we added a simple Cats static method to our HordeController. Although this works, it’s not the best way of passing data. Preferably, you should be using Models. Let’s create one!

Start by making a new folder called Models in your project.

Inside of that folder, create a new class and call it Cats.cs.

Let’s start by keeping it simple.

namespace MeowWorld.Models
{
    public class Cats
    {
        public string[] Names
        {
            get;
            set;
        }
    }
}

Now, in the Controllers\HordeController.cs, remove the Cats method and modify the All method so it creates a new Cats class and passes that on to the view.

[HttpGet("horde/all")]
public IActionResult All()
{
    var cats = new Models.Cats();

    cats.Names = _Cats.Keys.ToArray();

    return View(cats);
}

As you can see, we’re creating our new model, storing the data we want on it, and passing it along to the View. Now we need to edit the View to accept the model.

Open the Views\Horde\All.cshtml file and edit.

@model MeowWorld.Models.Cats

<html>
<body>
    The cats are:
    <ul>
        @foreach (var cat in Model.Names)
        {
            <li>@cat</li>
        }
    </ul>
</body>
</html>

Now, inside of your View, you have a @Model variable that the data your pass in your Controller will be set to.

It is possible to do more in a model, including all the logic you might want to do inside of your Controller. However, this is not recommended. You should put the bulk of your logic inside of the Controller (or off in other objects), use the Model to transfer data to the View, and then only use the View for rendering the data. You may still run into times when you need to put logic in the Model or View, and this is fine. These are just guidelines to follow in order to help keep your code clean and organized.

One nice benefit to keeping your Models lean is you’ll be able to just use them to store your data and pass them around throughout the rest of your code. Think of them as a POCO (Plain Old CLR Object).

Now that you know how to do everything, let’s put it all together to finish up our cat hoarding web app.

Cat View

First, let’s make a Model for the cat itself.

Model\Cat.cs

// Plain Old Cat Object
namespace MeowWorld.Models
{
    public class Cat
    {
        public string Name
        {
            get;
            set;
        }

        public string Sound
        {
            get;
            set;
        }
    }
}

Now let’s create a View for the cat:

Views\Horde\Cat.cshtml

@model MeowWorld.Models.Cat

<html>
<body>
    @if (@Model == null)
    {
        <i>Cat not found.</i>
    }
    else
    {
        <b>@Model.Name says:</b> @Model.Sound
    }
</body>
</html>

Notice how I’m checking if the Model is null. Depending on your situation, this can be important.

Now to add this to the Controller.

Controllers\HordeController.cs

[HttpGet("horde/cat/{cat}")]
public IActionResult Cat(string cat)
{
    Models.Cat model = null;

    if (_Cats.ContainsKey(cat))
    {
        model = new Models.Cat
        {
            Name = cat,
            Sound = _Cats[cat],
        };
    }

    return View(model);
}

And with that little bit of code, we’ve added a new web page for viewing the cats in HTML! Notice how I’m passing a null object to the View then checking for it? You don’t have to do things this way; you can instead have the Cat method in the Controller return a completely different View or just return some plain text like the API.

Now before we test it out, let’s make a change to the All.cshtml file.

@model MeowWorld.Models.Cats

<html>
<body>
    The cats are:
    <ul>
        @foreach (var cat in Model.Names)
        {
            <li><a href="/horde/cat/@cat">@cat</a></li>
        }
    </ul>
</body>
</html>

There, now our list of cats will have links going to each cat. Now start it up, Post a few cats, see Part 2 if you need… wait, this is a web app too now! Let’s add a form.

Forms

Adding a form in ASP.NET MVC is really simple. Let’s start by adding a new view.

Views\Horde\Add.cshtml

<html>
<body>
    <form method="post">
        Name:
        <input name="name" />
        <br />
        Sound:
        <input name="sound" />
        <br />
        <button>Add Cat</button>
    </form>
</body>
</html>

Now to add this to the Controller.

[HttpGet("horde/add")]
public IActionResult Add()
{
    return View();
}

[HttpPost("horde/add")]
public IActionResult Add(string name, string sound)
{
    _Cats[name] = sound;

    return Redirect("/horde/all");
}

Notice how on the Post method, I have it redirecting to All? This way the user can see the cat list after adding a cat to the horde. As usual, there are plenty of other ways to do something like this; this is just a simple one for the tutorial. Also, in practice, you’ll want to add checks to make sure the form is completed correctly and not trust user inputs. Trusting user inputs can have some unintended (and not very fun) unforeseen consequences.

Now that you have all of this done, run your project and navigate to .../horde/add/ in your browser and add a cat!

Once you add the cat, you should be redirected to the list of cats. But what if we want to add another cat? Oh no, we forgot to add a link to the add a cat form. That’s okay because we can do that right now, and we don’t even have to stop the code.

Editing A Razor File

The .cshtml files are able to be edited even if the site is up and running. Let’s quickly open up the Views\Horde\All.cshtml file and add a link back to the form at the bottom.

@model MeowWorld.Models.Cats

<html>
<body>
    The cats are:
    <ul>
        @foreach (var cat in Model.Names)
        {
            <li><a href="/horde/cat/@cat">@cat</a></li>
        }
    </ul>
    <a href="/horde/add">Add a Cat to the Horde!</a> <!-- Add this line. -->
</body>
</html>

Save the file and reload the web page. You should now see a link back to the form under the list of cats.

Now add all the cats you want to the horde and then click on one to see what it has to say.

Oh no! The same mistake was repeated here. Once again, we can quickly edit the Views\Horde\Cat.cshtml file and add a link back to the list.

@model MeowWorld.Models.Cat

<html>
<body>
    @if (@Model == null)
    {
        <i>Cat not found.</i>
    }
    else
    {
        <b>@Model.Name says:</b> @Model.Sound
    }
    <br /><br /><a href="/horde/all">See All</a> <!-- Add this line. -->
</body>
</html>

Now reload the page and you should have a link back to all the cats.

Now that your Cat Horde Web App is up and running, let’s add the latest build to OpenShift. Just like we did in the last tutorial, simply commit and push to GitHub. If you don’t have web hooks setup (an optional step in Part 3), rebuild it on OpenShift.

Conclusion

And there you have it, a cat horde web app! You started out with a simple Web API that returned static data and turned it into a dynamic Web App that you can interact with. Sure, it might be primitive, but I’m sure you can continue expanding on it on your own and grow it into something great.

I hope you found these tutorials useful for getting started with ASP.NET MVC as well as OpenShift. Be sure to watch for more OpenShift and .NET posts.

Now go out there and create some awesome containerized content! Have any other topics that you’d like to see addressed in this or another tutorial series? Leave a comment below.

Categories
.NET, OpenShift Container Platform, OpenShift Origin, Products
Tags
, ,