0% found this document useful (0 votes)
0 views

MVC Summary - Day 2

The document provides an overview of the IActionResult interface in ASP.NET MVC, detailing various classes like ContentResult, JsonResult, NotFoundResult, and FileResult that implement this interface for handling different response types. It explains how data is transferred between controllers and views using models, ViewData, and ViewBag, emphasizing the advantages of strongly-typed models over dynamic properties. Additionally, it covers form submission attributes and the Model Binder's role in mapping request data to controller action parameters.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

MVC Summary - Day 2

The document provides an overview of the IActionResult interface in ASP.NET MVC, detailing various classes like ContentResult, JsonResult, NotFoundResult, and FileResult that implement this interface for handling different response types. It explains how data is transferred between controllers and views using models, ViewData, and ViewBag, emphasizing the advantages of strongly-typed models over dynamic properties. Additionally, it covers form submission attributes and the Model Binder's role in mapping request data to controller action parameters.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

MVC Summary - Day 2

IActionResult

In ASP.NET MVC, IActionResult is your interface to various ways of


responding to user requests. It acts as a chameleon, adapting to different
content types and situations.
ContentResult is a class that implements IActionResult and returns a
string as the response body. It can be created using the ContentResult
constructor or the Content method of the controller.

JsonResult is a class that implements IActionResult and returns a JSON-


formatted object as the response body. It can be created using the
JsonResult constructor or the Json method of the controller.

NotFoundResult is a class that implements IActionResult and returns a 404


Not Found status code. It can be created using the NotFoundResult
constructor or the NotFound method of the controller.

FileResult is an abstract class that implements IActionResult and returns


a file as the response body. It has several subclasses that handle different
sources of files, such as FileContentResult and FileStreamResult . It can
be created using the File method of the controller, which accepts the file
path, the content type, and the file download name as parameters.

The "file download name" parameter is optional and can be skipped if the
browser should display the file instead of downloading it, if possible.
The "content type" parameter is a string that indicates the MIME type of the
file, such as “text/plain”, “image/png”, “application/pdf”, etc. It helps the
browser to interpret and render the file correctly. To determine the content
type of a file, one can use the [MIME types list](An Alphebetized List of MIME
Types (sitepoint.com) ) or the MIME types mapping in IIS.

How data is transferred between Controller and View?

RazorPage is an abstract class that represents the properties and methods


that are needed to render a view that uses Razor syntax. Any view in
ASP.NET Core MVC inherits from this class, either directly or indirectly.

Model:

A view can receive data from a controller by using the Model property, which
is a dynamic type. This means that the data can be any object, and the
compiler does not check the type or the properties of the object at compile
time. This is also called a loosely typed view.
To make a view strongly typed, we can use the "@model" directive to specify
the type of the Model property. This enables IntelliSense and compile-time
checking of the data, and makes the view more robust and maintainable.
To send multiple parameters to a view via the Model property, we can use a
List , an Array , a Dictionary , or any other collection type as the model.
However, this can make the view less readable and less reusable, as it does
not convey the meaning and the structure of the data.
A better alternative to collections is to use a ViewModel , which is a class that
contains the properties of the different types of data that we need to send to
the view. A ViewModel is not a representation of a database table, but a
representation of the data that the view needs.

To be able to use a view model in a view, we need to reference the


namespace where the view model class is defined, and use the
@model directive to specify the view model type.

To avoid repeating the using statement in every view, we can add it to the
(ViewImports.cshtml) file, which is a special file that applies to all views in the
same folder or subfolders. This way, we can access the view model type
without specifying the namespace in every view.

ViewData and ViewBag:

ViewData and ViewBag are both used to pass data from controllers to views.
ViewData and ViewBag are both dynamic properties of the ControllerBase
class, which is the base class of the Controller class.
They are both valid only during the current request and are cleared if
redirection occurs. They are also not checked at compile time, so they can
cause runtime errors if the keys or properties are misspelled or not defined.
ViewData is a dictionary of objects with a string-based key. It can store any
type of data, but it requires casting when retrieving the data in the view.

ViewBag is a dynamic wrapper around ViewData that provides dynamic


access to the objects stored in ViewData with a more convenient syntax. It
does not require casting when retrieving the data in the view, as it determines
data types at runtime.

But it does not support IntelliSense during compile time, which may
compromise type safety and clarity. Also, ViewBag 's dynamic nature might
have minor performance overhead.

Overall, Try utilizing strongly-typed Model or ViewModel for primary data


transfer. While using ViewData for small amounts of additional data or when
types are truly dynamic. Avoid excessive reliance on ViewBag , as it can
hinder code clarity and maintainability in larger projects.

The dynamic keyword is a special static type that allows you to use objects
without knowing their type at compile time. Similar to JavaScript, where you
can assign any value to a variable and access any property or method of an
object. However, this also means that you lose the benefits of static type
checking, such as compile-time errors, IntelliSense, and performance
optimization. Therefore, it is not generally recommended to use the dynamic
keyword unless you have a specific reason to do so.

View-to-Controller Communications:

The action attribute of a form element specifies the URL of the controller
action that will handle the form submission. The URL can be absolute or
relative to the current page. The action attribute is required for a form
element, otherwise the form will not be submitted. For example, if you have a
form that collects the user’s name and email, you can use the action attribute
to specify the URL of the controller action that will save the user’s information
and send a confirmation email.

The method attribute of a form element specifies the HTTP verb to use for
the form submission. The HTTP verb determines how the form data is sent to
the server and how the server responds to the request. The default method is
GET, which appends the form data to the URL as query string parameters.
This method is suitable for simple and idempotent requests, such as
searching or filtering data. However, this method also exposes the form data
in the URL, which can be insecure and unreliable. To hide the form data from
the URL, you can use POST instead, which sends the form data in the request
body. This method is suitable for complex requests, such as creating or
updating data.

The name attribute of an input element determines the key of the query
string parameter or the form data field that will be sent with the form
submission. The name attribute is required for an input element, otherwise
the input value will not be sent. The name attribute should be unique within a
form, unless you want to group multiple inputs with the same name. For
example, if you have an input that collects the user’s first name, you can use
the name attribute to specify that the input value should be sent as a query
string parameter or a form data field with the key “fname”.

The Request.Query property of a controller is a collection that contains the


query string parameters of the current request. The query string is the part of
the URL that follows the question mark (?) and consists of key-value pairs
separated by ampersands (&). The Request.Query property allows you to
access the query string parameters by their keys.

Model Binder:

The Model Binder is a feature that automatically maps the data from the
request to the parameters of the controller action. It uses the name of the
parameters and their properties to match them with the data from the
request. The model binder can also handle arrays or collections of
parameters, as long as the data from the request has the same name as the
parameter name. For example, if you have a controller action that takes a user
object as a parameter, you can use the model binder to populate the user
object from the data in the request.
The Model Binder will populate the user object from the data in the request.
For example, if the request has form data with the fields "name" and "email",
the model binder will assign them to the user.Name and user.Email properties.

The Model Binder searches for data in the following order: form data, route
data, query string.
Form data is the data that is sent in the request body when the form method
is POST.
Route data is the data that is extracted from the URL based on the route
template.
Query string is the data that is appended to the URL as key-value pairs when
the form method is GET. You can use attributes like [FromForm] ,
[FromQuery] , or [FromRoute] to specify a different source for a parameter.

Here, the model binder will get the id parameter from the route data, and get
the keyword parameter from the query string.

For example, if the URL is /Home/Details/42?keyword=asp.net, the model


binder will assign 42 to the id parameter, and assign "asp.net" to the
keyword parameter.

The Model Binder can also bind arrays or collections of parameters, as long
as the data from the request has the same name as the parameter name.
The model binder will use the value attribute of the input element if it is
present, or the text content of the input element if it is not. For example, if
you have a form that allows the user to select multiple degrees from a list,
you can use the name attribute to specify that the input values should be
sent as an array parameter named “degree”.

Here, if the Model Binder recognize that our action have a parameter (int[]
degree), it will automatically map it to the select element and store the
value of the chosen option elements. If the user choose Bachelor of
Science and Doctor of Philosophy, this view would return an array with the
values 100 and 300 when submitting the form.

You might also like