ASP.NET MVC: Transferring Data and Action Results

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson

Questions and Answers

Which property is used to transfer data from a controller to a view?

  • SessionState
  • ApplicationState
  • ViewBag (correct)
  • Cache

A view model is used to transfer data from a view to a controller.

False (B)

Which property is used to transfer data from one controller to another?

TempData

The __________ pattern is used to prevent resubmission of POST data.

<p>PRG</p> Signup and view all the answers

Match the ActionResult subtype with its intended use:

<p>ViewResult = Renders a view to the response. RedirectResult = Redirects to a specified URL. JsonResult = Returns a JSON-formatted response. FileResult = Sends a file as the response.</p> Signup and view all the answers

Which of the following best describes the difference between ViewData and ViewBag?

<p>ViewBag is strongly typed; ViewData is dynamically typed. (D)</p> Signup and view all the answers

The Keep() method in TempData ensures that data is available only for the current request.

<p>False (B)</p> Signup and view all the answers

What is the main purpose of the Peek() method in the TempData class?

<p>viewing <code>TempData</code> without deleting it</p> Signup and view all the answers

To pass data to a strongly-typed view, you should use a __________.

<p>view model</p> Signup and view all the answers

Match the method of the Controller class with its correct usage:

<p><code>View()</code> = Returns a <code>ViewResult</code> object. <code>Redirect()</code> = Returns a <code>RedirectResult</code> object. <code>RedirectToAction()</code> = Returns a <code>RedirectToActionResult</code> object. <code>Json()</code> = Returns a <code>JsonResult</code> object.</p> Signup and view all the answers

Which property of the ViewDataDictionary class returns the number of items it contains?

<p><code>Count</code> (B)</p> Signup and view all the answers

When using ViewBag, properties need to be cast to their specific types when accessed in the view.

<p>False (B)</p> Signup and view all the answers

In the NFL Teams app example, what is the purpose of the Conference and Division classes?

<p>represent team organization</p> Signup and view all the answers

The two conferences in the NFL are the __________ and __________.

<p>NFC, AFC</p> Signup and view all the answers

Match each ActionResult subtype with its scenario of when it should be used:

<p><code>RedirectResult</code> = For redirecting to an external website. <code>LocalRedirectResult</code> = For redirecting within the current application. <code>RedirectToActionPermanent</code> = For a permanent redirect to a different action. <code>JsonResult</code> = For returning data in JSON format.</p> Signup and view all the answers

Why might you choose to use ViewData over ViewBag?

<p>All of the above (D)</p> Signup and view all the answers

The HTTP status code 302 indicates a 'Moved Permanently' redirection.

<p>False (B)</p> Signup and view all the answers

Which method is used to ensure that TempData persists across redirects?

<p>Keep()</p> Signup and view all the answers

In ASP.NET Core MVC, the interface at the top of the ActionResult hierarchy is _________.

<p>IActionResult</p> Signup and view all the answers

Match each method used to redirect to another action with the correct number of arguments it accepts:

<p>Action Method = One argument Action Method and Controller = Two arguments Action Method and Routes = Two arguments Action Method, Controller, and Routes = Three arguments</p> Signup and view all the answers

Which of the following best describes the purpose of using a view model?

<p>To strongly type the data passed from the controller to the view. (C)</p> Signup and view all the answers

If you do not call Keep() on a TempData item, it will automatically persist for the next three requests.

<p>False (B)</p> Signup and view all the answers

Name two properties available on the ViewDataDictionary class.

<p>Count, Keys</p> Signup and view all the answers

The primary purpose of the ActionResult subtype __________ is to send a file to the client's browser.

<p>FileResult</p> Signup and view all the answers

Match the NFL division with the type of direction:

<p>North = Direction South = Direction East = Direction West = Direction</p> Signup and view all the answers

In the NFL Teams app, what data does the Team class contain?

<p>TeamID, Name, LogoImage, Conference, and Division (A)</p> Signup and view all the answers

The custom route in Program.cs maps URLs to specific controllers and actions.

<p>True (A)</p> Signup and view all the answers

What does the @RenderBody() method in the layout file do?

<p>renders the content of the view</p> Signup and view all the answers

The __________ method is used to cast ViewData to double type.

<p>(double)</p> Signup and view all the answers

Match each of the example action methods with their name:

<p>List() = Returns a ViewResult object Index() = Returns a RedirectToActionResult object Edit() = Returns different types of result objects</p> Signup and view all the answers

Which statement is most accurate regarding the ActionResult hierarchy?

<p><code>ActionResult</code> implements <code>IActionResult</code> (C)</p> Signup and view all the answers

Using the PRG pattern, if a user refreshes the redirected page, they will resubmit the form data.

<p>False (B)</p> Signup and view all the answers

What does the acronym PRG stand for?

<p>Post Redirect Get</p> Signup and view all the answers

The __________ method can be used to view TempData without deleting it from TempData.

<p>Peek()</p> Signup and view all the answers

Match the term used to redirect with the direction of where it redirects:

<p>RedirectResult = External URL LocalRedirectResult = URL within app RedirectToActionResult = Action method within the app RedirectToRouteResult = Named route</p> Signup and view all the answers

Which of the following code snippets is an example of controller code that adds two items to the ViewData property?

<p><code>public ViewResult Index() {\n ViewData[\&quot;Book\&quot;] = \&quot;Alice in Wonderland\&quot;;\n ViewData[\&quot;Price\&quot;] = 9.99;\n return View();\n}</code> (B)</p> Signup and view all the answers

ViewBag properties can be used without casting.

<p>True (A)</p> Signup and view all the answers

What type of object does the View() method return?

<p>IActionResult</p> Signup and view all the answers

The __________ method is a method used to help determine the active link on the view.

<p>CheckActiveConf()</p> Signup and view all the answers

Match the overload of the View() method with the description:

<p>View() = No parameters provided. View(model) = Model parameter is passed in. View(name) = Name parameter is passed in. View(name, model) = Name and Model parameters are passed in.</p> Signup and view all the answers

Flashcards

ActionResult

Represents the result of an action method.

ViewBag

Transfers data from a controller to a view using dynamic properties.

ViewData

Transfers data from a controller to a view using a dictionary-like structure.

TempData

Used in web applications to redirect and transfer data from one controller to another.

Signup and view all the flashcards

PRG Pattern

A design pattern used to prevent the resubmission of POST data when a user refreshes a page.

Signup and view all the flashcards

View Model

A class used to transfer data from a controller to a strongly-typed view.

Signup and view all the flashcards

ViewResult

Represents the result of a controller action that renders a view.

Signup and view all the flashcards

RedirectResult

Represents the result of a controller action that performs a redirection.

Signup and view all the flashcards

RedirectToAction

Represents the result of a controller action that redirects to another action.

Signup and view all the flashcards

JsonResult

Represents the result of a controller action that returns JSON (JavaScript Object Notation).

Signup and view all the flashcards

FileResult

Represents the result of a controller action that returns a file.

Signup and view all the flashcards

EmptyResult

Represents the result of a controller action that returns an empty result.

Signup and view all the flashcards

Redirect()

Returns a redirect response with 302 status code.

Signup and view all the flashcards

RedirectPermanent()

Returns a redirect response with 301 status code.

Signup and view all the flashcards

Keep() method

Retains a TempData value for the subsequent request.

Signup and view all the flashcards

Peek() method

Checks the value of a TempData and retains the temp data.

Signup and view all the flashcards

Study Notes

  • Transferring data from controllers involves using ViewBag and ViewData properties.
  • Using a view model transfers data from a controller to a strongly-typed view.
  • TempData property enables web apps to redirect and transfer data from one controller to another.
  • Important interfaces and classes form the ActionResult hierarchy.
  • One needs to distinguish between the ViewBag and ViewData properties.
  • A view model transfers data from a controller to a view.
  • Action methods can redirect to other action methods.
  • The PRG pattern prevents resubmission of POST data.
  • Distinctions exist between the ViewData and TempData properties.
  • The Keep() and Peek() methods serve specific purposes within the TempData class.

ActionResult Hierarchy

  • The hierarchy includes IActionResult(interface).
  • It also includes ActionResult(abstract), and ViewResult.
  • RedirectResult, JsonResult, and FileResult are also part of the hierarchy.

Common ActionResult Subtypes

Controller Class Methods (ActionResult)

  • The Controller class has methods that return an ActionResult object, like View(), Redirect(), and RedirectToAction().
  • File() and Json() are also methods that return an ActionResult object.

Overloads of the View() method

  • Overloads include View(), View(model), View(name), and View(name, model).

ViewResult Object Example

  • To return a ViewResult object, follow this exampple: public ViewResult List() {var names = new List<string> { "Grace", "Ada", "Charles" };return VIew(names);}

RedirectToActionResult Example

  • An action method to return a RedirectToActionResult object: public RedirectToActionResult Index() => RedirectToAction("List");

Action Method with Different Result Types

  • Example of an action method returning different result object types : [HttpPost] public IActionResult Edit(string id) { if (ModelState.IsValid) {return RedirectToAction("List");} return View((object)id);}

ViewData Property

  • Adding items to the ViewData property in controller code: public ViewResult Index() { ViewData["Book"] = "Alice in Wonderland"; ViewData["Price"] = 9.99; return View();}

ViewDataDictionary Class Properties

  • Includes Count, Keys, and Values.

Razor Code to Show ViewData Items

  • Sample Razor code displays all items in the ViewData object: <h2>@ViewData.Count items in ViewData</h2> @foreach (KeyValuePair<string, object?> item in ViewData) { <div>@item.Key - @item.Value</div> }
  • Output is 2 items in ViewData, "Book - Alice in Wonderland", and "Price - 9.99".

Casting a ViewData Object

  • Razor code casts a ViewData object to a double type: <h4>Price: @(((double)ViewData["Price"]).ToString("c"))</h4>
  • Results in "Price: $9.99" in browser.

Checking ViewData for Null

  • Razor code checks ViewData for null: <h4>Price: @(((double?)ViewData["Price"])?.ToString("c"))</h4>
  • It casts a value type (double) to a nullable type.
  • It also casts a reference type (string) to a nullable type using: <h4>Book: @ViewData["Book"]?.ToString().ToUpper()</h4>

ViewBag Property Example

  • Controller code adding dynamic properties to the ViewBag: public ViewResult Index() { ViewBag.Book = "Alice in Wonderland"; ViewBag.Price = 9.99; return View();}

Razor Code to show ViewBag Properties

  • Razor code displays ViewBag properties using ViewData: <h2>@ViewData.Count ViewBag properties</h2> @foreach (KeyValuePair<string, object?> item in ViewData) { <div>@item.Key - @item.Value</div> }
  • The browser shows "2 ViewBag properties" with "Book - Alice in Wonderland" and "Price - 9.99".

Working with ViewBag (No Casting)

  • Razor code works with a ViewBag property without casting: <h4>Price: @ViewBag.Price.ToString("c")</h4>
  • The view displays "Price: $9.99".

Checking ViewBag Properties for Null

  • Razor code example: <h4>Price: @ViewBag.Price?.ToString("c")</h4>
  • Used for a value type (double).
  • Razor code example: <h4>Book: @ViewBag.Book?.ToUpper()</h4>
  • Used for a reference type (string).
  • The Key name must be valid to be used in C#.
  • Can call properties and methods of the ViewDataDictionary class.
  • You can loop through all the items in the ViewData dictionary.

NFL Team Organization

  • The teams of the National Football League (NFL) are organized in two conferences: NFC and AFC.
  • Four divisions exist within each conference: North, South, East, and West.
  • Four teams per division.

Conference Class Definition

  • Defines the structure for conference data with properties for ConferenceID and Name.

Division Class Definition

  • Includes properties for DivisionID and Name.

Team Class Definition

  • Contains properties for TeamID, Name, Conference, Division, and LogoImage.

TeamContext Class

  • Sets up the database context, including seeding initial data like conference and division names.

Home Controller Details

  • HomeController class manages the interactions and data retrieval for the NFL Teams app.
  • Methods store selected conference and division IDs in the view bag, and retrieves conference and division data from the database.
  • Filters teams by conference and division, passes the list of teams to view as a model.

Custom Route

  • The custom route in Program.cs defines a specific route pattern for conference and division display.
  • A default route is also present.

Layout

  • The layout includes meta, links to bootstrap and site css.
  • It loads in the ViewBag title.

Home/Index View:

  • It displays team data based on the model passed from the controller.
  • Loops through conferences and divisions to create links.
  • Loops through teams to display their logos and names.

TeamsViewModel class

  • A view model provides a structured way to pass data to the view.
  • A view model is used including lists of teams, conferences, and divisions, along with methods to determine active links.

Updated Home Controller

  • Populates the model with the lists of teams, conferences, and divisions.

Updated Home/Index View

  • Loops to generate appropriate HTML elements for dynamic content display.

HTTP Status Codes (Redirection)

  • 302 Found, and 301 Moved Permanently are used for redirection.

ActionResult Subtypes (Redirection)

  • Includes RedirectResult, LocalRedirectResult, RedirectToActionResul, RedirectToRouteResult.
  • Redirect() is a 302 Found method, RedirectPermanent() is a 301 Moved Permanently method.
  • LocalRedirect() is a 302 Found method, LocalRedirectPermanent() is a 301 Moved Permanently method.
  • RedirectToAction() is a 302 Found method, RedirectToActionPermanent() is a 301 Moved Permanently method.
  • RedirectToRoute() is a 302 Found method, RedirectToRoutePermanent() is a 301 Moved Permanently method.

Subtype Usage (Redirection)

  • RedirectResult is used to redirect to an external URL.
  • LocalRedirectResult ensures redirection happens within the app.
  • RedirectToActionResult redirects to an action method within the app.
  • RedirectToRouteResult redirects using a named route within the app.

RedirectToAction() Overloads

  • (a): Redirects to the specified action in current controller.
  • (a, c): Redirects to the specified action in specified controller.
  • (a, routes): Redirects to the specified action in the current controller using route parameters.
  • (a, c, routes): Redirects to the specified action in the specified controller using route parameters.

Redirecting Action Methods

  • In the current controller: public RedirectToActionResult Index() => RedirectToAction("List");
  • In the Team controller: public RedirectToActionResult Index() => RedirectToAction("List", "Team");
  • With a parameter in current controller: public RedirectToActionResult Index(string id) => RedirectToAction("Details", new { ID = id });
  • Use shortcut for variable and route segment name match: public RedirectToActionResult Index(string id) => RedirectToAction("Details", new { id });
  • To supply parameters with a string-string dictionary: public RedirectToActionResult Index(string id) => RedirectToAction("Details", new Dictionary<string, string>(){ { "ID", id } });

Browser Message (POST Request)

  • Browsers display a confirmation message when refreshing a page displayed by a POST request
  • The purpose is to prevent resubmission.

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

Related Documents

More Like This

Asp .Net MVC Architecture
5 questions

Asp .Net MVC Architecture

CooperativePearTree avatar
CooperativePearTree
Overview of ASP.NET MVC Framework
11 questions

Overview of ASP.NET MVC Framework

HeartfeltPhosphorus9547 avatar
HeartfeltPhosphorus9547
Use Quizgecko on...
Browser
Browser