Passing data to view

Passing Data from the Controller to the View

Controller actions are invoked in response to an incoming URL request. A controller class is where the code is written that handles the incoming browser requests. View templates can be used from a controller to generate and format an HTML response to the browser.

Controllers are responsible for providing the data required in order for a view template to render a response, However, view templates should not do business logic or Interact with a database directly!

A view template should work only with the data that's provided to it by the controller. Maintaining this "separation of concerns" helps keep the code clean and testable!

How to pass data from the controller to view?

Currently, the Welcome method in the HelloWorldController class takes a name and an ID parameter and then outputs the values directly to the browser. Rather than have the controller render this response as a string, change the controller to use a view template instead.

The view template generates a dynamic response, which means that appropriate data must be passed from the controller to the view to generate the response. Do this by having the controller put the dynamic data (parameters) that the view template needs in a ViewData dictionary.

The view template can then access the dynamic data. The ViewData dictionary is a dynamic object, which means any type can be used. The ViewData object has no defined properties until something is added.

We can pass date to view by having the controller put the data that the view template needs in a ViewData dictionary (a structure to store key-value pairs provided by the ASP.NET framework)

Let's make the changes to the code

Modify the HelloWorldControllerso it looks like this now

using Microsoft.AspNetCore.Mvc;
using System.Text.Encodings.Web;

namespace MvcMovie.Controllers;

public class HelloWorldController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
    public IActionResult Welcome(string name, int numTimes = 1)
    {
        ViewData["Message"] = "Hello " + name;
        ViewData["NumTimes"] = numTimes;
        return View();
    }
}

Create a Welcome view template named Views/HelloWorld/Welcome.cshtml.

You'll create a loop in the Welcome.cshtml view template that displays "Hello" NumTimes. Replace the contents of Views/HelloWorld/Welcome.cshtml with the following:

@{
    ViewData["Title"] = "Welcome";
}

<h2>Welcome</h2>

<ul>
    @for (int i = 0; i < (int)ViewData["NumTimes"]!; i++)
    {
        <li>@ViewData["Message"]</li>
    }
</ul>

Save your changes and browse to the following URL:

https://localhost:{PORT}/HelloWorld/Welcome?name=Rick&numtimes=4

Data was taken from the URL and passed to the controller using the MVC model binder. The controller packaged the data into a ViewData dictionary and passed that object to the view. The View then rendered the data as HTML to the browser!

Last updated