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.
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
Let's add code to our new model file. We'll first declare a namespace and class:
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:
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.
Models
subdirectory of the production project.namespace ProjectName.Models
{
public class ClassName
{
}
}
Lesson 14 of 38
Last updated more than 3 months ago.