SeanMcCammon C# .Net core 3 Software Developer

Let me start this post by saying if you're already know how to pass data from the backend code to your front end: this post is not for you. This post if for people who are just learning how to do this.

Let's face the facts here. You're most likely creating an ASP.NET App and pages to allow you to take in data and use data dynamically on the front end.

What would be the use of a page written in a dynamic language such as C# and using ASP.NET if it were just static data? You may as well use just HTML to create the webpage.

However, you may be wondering how you can pass this data from the back end code into the front end page.

In this article, we're going to go through 3 ways of getting this data from the code and into your webpage front end.

One more thing I want to note. I am not going to go into the reasons why there are are a few different ways to pass in data. I am just going to show you how to use them. If you want the history of why they exist then this can be an assignment for you. Just know that knowing why they were created doesn't take away from knowing how to use them and visa versa.

Using ViewBag

ViewBag is the first method we are going to be using to pass information/variables from your controller code and into your view.

ViewBag allows you to assign some temporary values in your controller and use them in the view.

You assign the values in your controller method: ViewBag.Title = "My Title" as in the below code snippet:

public IActionResult Index()
{
    ViewBag.Title = "My Webpage App";
    return View();
}

When this controller code is called, when you navigate to the page, the value of "My Webpage App" is assigned to the temporary ViewBag.Title.

Then in the view, to use this you would do something as follows: <h1>@ViewBag.Title</h1>. The below View uses the above title in its page

<div class="text-center">
    <h1>Welcome to @ViewBag.Title</h1>
</div>

When this code runs, on the page you will see the header:

My Webpage App

ViewBag only transfers data from controller to view, not visa-versa. ViewBag values will be null if redirection occurs.

Using ViewData

The next way of passing data into your view that we are going to look at is ViewData.

ViewData is very similar to ViewBag and was created for a specific reason. As I said, I won't go into whys; just the hows.

Like ViewBag, ViewData allows you to pass in temporary values from the controller code into the view.

So, how do we use ViewData? It's quite similar to ViewBag except how you reference the data.

To add some data into ViewData you assign it as follows: ViewData["Title"] = "My Webpage App"

The following code snippet shows it in action.

public IActionResult Index()
{
    ViewData["Title"] = "My Webpage App";
    return View();
}

To use a ViewData in your view you reference it as follows @ViewData["Title"]

The following code snippet is this being used in a view:

<div class="text-center">
    <h1>Welcome to @ViewData["Title"]</h1>
</div>

You may notice a lot of similarity between how you use ViewBag and ViewData. The obvious difference is how you reference the data, one being with a dot and the other enclosed in square brackets and surrounded by quote marks.

You could even use both in a controller and view; however, you would need to use different values of reference. So, in the above example, you could not have them both using "Title", but you could have "ViewBagTitle" and "ViewDataTitle" for example.

Using Model

The third way of passing data into your view that we are going to look at is Models.

You may have already come across models as the ASP.NET applications are MVC - Model, View, Controller applications. You model is the part that contains the data for the application.

In the case of using ViewBag and ViewData you can create temporary data variables as you need them in the controller. Using models are a little more in-depth.

Unlike just assigning a value in a ViewBag or ViewData: for a model you need to first define the model class, then create an object and pass in the data.

For this example, I am going to create a simple model; assigned data and then use it in my view.

First, let us create a very simple model:

using System;
namespace TestMVCApp.Models
{
    public class TitleModel
    {
        public string Title { get; set; }
    }
}

Normally the model would be more complex than this; I would probably never use a model to pass in the title for example. Examination of this simple model shows that it contains one string called Title.

Next, we use this class in our controller, create an object and assign a value as in the following code snippet:

public IActionResult Index()
{
    TitleModel titleModel = new TitleModel();

    titleModel.Title = "My Webpage App";
    return View(titleModel);
}

Notice also, with this example of model, we pass in the model in the View command; something we didn't do for ViewBag and ViewData.

Finally, let us look at the View using this model:

@model TitleModel

<div class="text-center">
    <h1>Welcome to @Model.Title</h1>
</div>

Again, you can see with the model that there is a little more to it. Firstly we have to define the model we are using by using the @model command. Then to get access to the data we need to use @Model.Title.

This may seem like a little more effort, but the great thing about using a model is that it's not just temporary data. You create your object and assign values to it.

In the controller code, you could then pass this model into other methods to manipulate that data; then pass this into the view. You could have list's in your model and do things like @foreach to step through the list of data.

Using a model allows you to pass more complex data into your view and really should be the method you are using to create your dynamic views.

Using more than one method

In practice I find myself using a combination of the above. I tend to use models for passing in my dynamic data - passing information back and forth between the view and controller.

I then use ViewBag (and sometimes ViewData) to pass in smaller items such as the title or some other small data that I don't need to put into a model.

For example, I would not put the title of the page in the model; that I would use ViewBag for.

Using these methods will allow you to pass data from your controller into your views and allow you to create your ASP.NET app using the MVC model.

If you’re anything like me: when you wanted to find out more about ASP.NET you went to the internet.

May be you went to an online site that has training courses such as Udemy. Maybe you searched and found some tutorial pages. 

Me personally, I did both and after trying to follow some of these I found information that had gone out of date.

starting wit information I leant for Route

When I was trying to add a custom route to a page/method - I followed a course which told me to add it to RouteConfig.cs.

Configure the new route for my custom page and inputs in using MapRoute().

With a default .Net Core MVC build in Visual Studio 2019 this file was not in the project.

Examining the default C# files; in Startup.cs the endpoints are mapped using MapControllerRoute().

This worked well but did not give me the flexibility I was after. 

What I really wanted was to have a custom route defined for specific methods in my class that managed a single page.

For example: if I have a page called Movie. I wanted a page that maybe called Random. I then may want a page that displays Movie Titles or Authors.

Using the MapControllerRoute was starting to get a little clunky (using a technical term there) and did not give me the flexibility I needed. So, I decided to use Route in the controller.

Custom routes in the controller

Using this method of adding custom routes allows you to add a route per method for you controller.

So, as an example

Route(“Movie/Author/{name}”)]
Public IActionResult ByAuthor(string name) {...} </code></p>

The above allows us to go to a page named Http://our_site/Movie/Random

And also a page where we pass in a parameter Http://out_site/Movie/Author/Sean

In the above, Sean is passed is as a parameter and goes into the name parameter. We can then search our list of movies for the author name and output content found.

Both these methods would exist in the controller - which maybe named MovieController.cs

The best way to route in ASP.NET code

This, in my opinion, is the best way too route to pages in your ASP.NET code. Each method has its own custom route defined which includes any parameters. 

You don’t need to add any code for the route into your startup.cs file; as it’s all contained in the controller file.

I wanted to start this post with a quick caveat. At the time of writing this post: the .Net Core3 is currently at Preview 8.

As we grow closer to the September release date I hope that many of the code and feature I talk about in my upcoming blog posts will remain the same.

However, I may have to come back to some of them in the future to fine tune.

That said, let us begin

Why write about .Net Core 3?

So, if you look at my previous posts on this site: most are technical. None of them really go into too many specifics apart from any coding examples.

I’m now on a journey myself: a journey of learning about .Net Core 3. A journey that is a discovery of all the new features - but also older features that have not changed.

A journey that will see me work with and code new products. A journey that will also see me learning more about ASP.NET as this is something I have not used commercially.

So, as I travel along this learning journey I thought I would share with you all the things I learn. 

The initial posts maybe more suited to people who are starting to learn C# or .Net Core 2/3 - but I hope to get more technical as the posts go on.

So who maybe interested in these posts?

As I said above. My original though is, that, many of the people interested in these posts will be those on a learning journey.

However, it may be that, you may who already has knowledge of .Net Core 2 and want to see what has changed: see what has changed from my perspective and journey.

These are the main persons who I would think this blog of interest. Though I expect it could be useful to other groups. Whoever is reading this post and any others: welcome to my blog and I hope to interact with you.

More posts to come

So, this is really just an introduction to this new series of posts. I wanted to just say hi and detail a little of what I expect to write.

I do have more posts to write. Posts that will start to delve into a little more detail: such at [Route] for custom routes above methods.

So if you think this is something you will enjoy or find useful for you to read; keep popping back for the latest updates.

See you soon in the next and first post of this series.

linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram