Lesson Weekend

We've covered both the V and the C in MVC but we haven't gotten to M yet - the model. Remember that a model represents data. Currently, the controller in our virtual postcard application just passes along strings and a view. Let's create a class to model what our application's data should look like.

Model File Structure


Models always reside in a Models subdirectory of the production project. Create a Models subdirectory in FriendLetter. In Models, add a file named LetterVariable.cs.

The resulting file structure for models looks like this:

FriendLetter.Solution
└── FriendLetter
    ├── Models
        └── LetterVariable.cs

Writing a Model


Let's add code to our new model file. We'll first declare a namespace and class:

FriendLetter/Models/LetterVariable.cs
namespace FriendLetter.Models
{
  public class LetterVariable
  {

  }
}

We place the LetterVariable class in a FriendLetter.Models namespace. This means that any other files that need access to our model's logic can import it with the statement using FriendLetter.Models;.

FriendLetter.Models is similar to the namespace of our main project, FriendLetter. It doesn't actually matter if the FriendLetter portion is included in both namespace names, but it's good practice to give namespaces names that clearly denote their relation to the larger app. In our case, the FriendLetter.Models name is ideal because this namespace contains all the models in our FriendLetter project. To find out more about naming conventions, check out the Microsoft documentation.

Next, we'll add an auto-implemented property Recipient to our new model class:

FriendLetter/Models/LetterVariable.cs
namespace FriendLetter.Models
{
  public class LetterVariable
  {
    public string Recipient { get; set; }

  }
}

Our model is very simple. We can get and set a Recipient. That's all we need to explore using Razor to dynamically render our views. In future lessons, we'll develop more complex models.

Sample Model


  • Models always reside in a Models subdirectory of the production project.
ProjectName/Models/ClassName.cs
namespace ProjectName.Models
{
  public class ClassName
  {

  }
}

Lesson 14 of 38
Last updated more than 3 months ago.