CodeBehind Framework - Add Model in View
Tags: tutorial, dotnet, beginners, backend
Published: 2024-05-31 23:03:36

In this tutorial, we teach how to add a Model in View.

## Create an application with only View and Model

In the CodeBehind framework, you can create different parts of the program based on MVC, Model-View, Controller-View and only View architectures.

![Model-View Architecture in CodeBehind Framework](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0txnu4u15gdrt0p8u2tw.png)

Following the Model-View pattern allows you to build simple yet powerful applications. In this architecture, you add a Model class as a page attribute in the View, and the program automatically places the Model values ​​in the View page.

Example:

View
```html
@page
@model MyModel

<div>
    <b>@model.Value1</b>
    <br>
    <b>@model.Value2</b>
</div>
```

Model
```csharp
using CodeBehind;

public partial class MyModel : CodeBehindModel
{
	public string Value1 { get; set; }
	public string Value2 { get; set; }

	public MyModel()
	{
		Value1 = "This is text of Value1";
		Value2 = "This is text of Value2";
	}
}
```

The response that is sent to the browser is according to the codes below.

HTML result
```
<div>
    <b>This is text of Value1</b>
    <br>
    <b>This is text of Value2</b>
</div>
```

## CodeBehindModel abstract class

Adding the `CodeBehindModel` abstract class to the Model class will provide useful features for the Model class. In the following, we introduce the features of the `CodeBehindModel` abstract class with examples.

**ViewData**
ViewData is a name and value instance of the `NameValueCollection` class that is used to transfer data from the Model to the View.

You can set ViewData in the Model class as follows.
`ViewData.Add("title", "Hello World!");`

Then you can call ViewData as shown below.
`<title>@ViewData.GetValue("title")</title>`

**Section**
Section is a attribute that applies to aspx pages. Section is a feature whose activation makes all paths after the aspx path refer to the current aspx path.

Section in Model takes its value only when you have activated Section in your View. In the next trainings, we will teach Section completely.

Example:

Active Section in View
```html
 @page
+@section
```

If you enable Section in the `/page/about.aspx` path, any path added after the current path will be considered a Section and the executable file in the `/page/about.aspx` path will still be executed.

Example:

`/page/about.aspx/section1/section2/.../sectionN`

If you enable the Section in an executable file called `Default.aspx`, you will still have access to the default path.

Example:

`/page/about/Default.aspx/section1/section2/.../sectionN`

or

`/page/about/section1/section2/.../sectionN`

**CallerViewPath**
The View path that requests the current Model.

Example:

If the request path is the following value:
`example.com/page/about/OtherInfo.aspx`
According to the above value, the following string is stored in CallerViewPath:
`/page/about/OtherInfo.aspx`

**CallerViewDirectoryPath**
The View directory path that requests the current Model.

Example:

If the request path is the following value:
`example.com/page/about/OtherInfo.aspx`
According to the above value, the following string is stored in CallerViewDirectoryPath:
`/page/about`

**Download**
Download is a method that takes the file path as an input argument and makes the file available for download in the View path.

Example:
```csharp
Download("/upload/book/my_book.pdf");
```

**Write**

This method adds string values ​​to the beginning of the View page

Example:
According to the previous example, if you call the following method in the Model class, the string `New written text` will be added at the beginning of the View response.

`Write("New written text")`

The response that is sent to the browser is according to the codes below.

HTML result
```
New written text
<div>
    <b>This is text of Value1</b>
    <br>
    <b>This is text of Value2</b>
</div>
```

## Using CodeBehindConstructor method

In the previous example, we created an instance of the class constructor to set the properties. In the CodeBehind framework, you will not have access to all the features of the `CodeBehindModel` abstract class in the constructor class. But don't worry, you can use the CodeBehindConstructor constructor method in the Model class.

Example:

View (`/page/MyPage.aspx`)
```html
@page
@model MyModel()

<div>
    <b>@model.Value1</b>
    <br>
    <b>@model.Value2</b>
    <br>
    <b>View requested in the page directory? @model.LoadInPageDirectory</b>
    <br>
    <b>View directory path: @model.CallerViewDirectoryPath</b>
</div>
```

The CodeBehind constructor is activated when you use open `(` and close `)` parentheses in front of the class name in the View.

Example:
`@model MyModel()`

Model
```csharp
using CodeBehind;

public partial class MyModel : CodeBehindModel
{
	public string Value1 { get; set; }
	public string Value2 { get; set; }
	public string LoadInPageDirectory { get; set; }

	public void CodeBehindConstructor()
	{
		Value1 = "This is text of Value1";
		Value2 = "This is text of Value2";
		LoadInPageDirectory = CallerViewPath.StartsWith("/page/")? "Yes" : "No";
	}
}
```

The response that is sent to the browser is according to the codes below.

HTML result
```html
<div>
    <b>This is text of Value1</b>
    <br>
    <b>This is text of Value2</b>
    <br>
    <b>View requested in the page directory? Yes</b>
    <br>
    <b>View directory path: /page</b>
</div>
```

## View class without abstract

Example:

You can also create the Model class without the `CodeBehindModel` abstract. For this, it is necessary to put the name of the Model class between open `{` and closed `}` brackets in the View page.

Example:
`@model {MyModel}`
or
`@model {YourProjectName.DefaultModel}`

> Note: Please note that if you create the Model without the `CodeBehindModel` abstract class, you will not have access to the methods and attributes of the `CodeBehindModel` class. If you use the Model-View pattern to develop applications, it is better to create the Model class by adding the `CodeBehindModel` abstract.

## Model-View in Visual Studio Code

In the Visual Studio Code project, we create a new View named `ViewModel.aspx`.

In the Explorer section, by right-clicking on `wwwroot` directory, we select the `New File` option and create a new file called `ViewModel.aspx`.

Then we add the following codes inside the `ViewModel.aspx` file.
```html
@page
@model ViewModel()
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>@ViewData.GetValue("title")</title>
</head>
<body>
    <p>@model.BodyValue</p>
    <b>View path: @model.CallerViewPath</b>
    <br>
    <b>View directory path: @model.CallerViewDirectoryPath</b>
</body>
</html>
```

Then we create a Model named `ViewModel.cs`.

In the Explorer section, by right-clicking on an empty space in Explorer, we select the `New File` option and create a new file called `ViewModel.cs`.

Then we add the following codes inside the `ViewModel.cs` file.
```csharp
using CodeBehind;

public partial class ViewModel : CodeBehindModel
{
    public string BodyValue{ get; set; } = "";

    public void CodeBehindConstructor()
    {
        BodyValue= "The body tag is used in HTML to define the main content of a web page.";
        ViewData.Add("title", "Hello World!");
    }
}
```

We run the project (F5 key). After running the project, You need to add the string `/ViewModel.aspx` to the URL.

The response that is sent to the browser is according to the codes below.

HTML result

```html
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Hello World!</title>
</head>
<body>
    <p>The body tag is used in HTML to define the main content of a web page.</p>
    <b>View path: /ViewModel.aspx</b>
    <br>
    <b>View directory path: /</b>
</body>
</html>
```

For more practice, you can add a new attribute like BodyValue in the Model and call it in the View. You can also use the Write method in the Model and see the result in the View.

## Why use ViewData

Perhaps, after reading this tutorial, you may have a question; why do we use ViewData? Instead of using ViewData why don't we add an attribute in the Model class to call in the View?
ViewData is most useful when we use Layouts. In the next tutorials, we will explain Layout.

### Related links

CodeBehind on GitHub:
https://github.com/elanatframework/Code_behind

CodeBehind in NuGet:
https://www.nuget.org/packages/CodeBehind/

CodeBehind page:
https://elanat.net/page_content/code_behind