SlideShare a Scribd company logo
1 of 15
MVC Controllers
Controller
 This is what we have learned about ‘controller’ so far:
 It is one of the three MVC components
 It is a C# class that contains action methods
 An action method is a method that runs in response to a request
 It is the entry point when a HTTP request is received
 Depending on the request, the controller may get the requested data from
the model or update the model data
 Then the controller selects a View to display, passing data to it
 In this chapter, we will have a closer look at controllers
Request, controller and binding model
 The first step when the MvcMiddleware receives a request is routing the
request to an appropriate controller
 Routing takes the path of the request, and maps it to one of the actions in
the controller
 Once an action is selected, if the request has data, a binding model is
generated
 A binding model is an object that acts as a “container” for the data
provided in a request
 Data could be part of the URL, query string, headers, or form fields
Request, controller and binding model
 Some action methods do not have parameters, for example a request to
display the home page, like the one below:
public IActionResult Index()
{
}
 This action method does not use a binding model, if one is created
 However, some action methods have parameters; they are used to receive
data contained in the request
Request, controller and binding model
 When ‘Submit Order’ is clicked, the request is mapped
to this action of HomeController, because of the
HTTPPost attribute
 An object (of the OrderModel type) is created using
the data entered in the Index view (customer, item,
price, quantity). This is the binding model
 This object (the binding model) is passed to the action
method. So, the parameter ‘model’ of the Index
method holds the binding model
[HTTPPost]
public IActionResult Index(OrderModel model)
{
ViewBag.AmtDue = model.CalculateAmountDue();
return View();
}
Validation
 Next, the action method:
1. Validates the data contained in the binding model
2. Invokes the appropriate actions on the application model
3. Generates a response based on the output from the application model
 Below is an illustration of Step 1, validation:
public IActionResult Search(OrderModel model)
{
if(ModelState.IsValid)
{
……
return View();
}
return Redirect("/")
}
 ModelState is a property inherited from the Controller class
Using the application model
 Step 2 is illustrated below, from the Order Processing example:
ViewBag.AmtDue = model.CalculateAmountDue();
 In this case, our application model consists of a single class, OrderModel
and controller is invoking a method of this class
Generating response
 Step 3, the action method selects the view template and passes the view
model to it, if applicable
 View model is an object required by the view to generate a UI
 View model can be one of business logic classes, for example Order class,
or
 It can be a class created specifically to represent the structure of the data
needed by a view
 We will look at these types of models in the future
Action methods
 Any public method on a controller acts as an action method
 To review, the responsibility of an action method is generally threefold:
 Confirm the incoming request is valid
 Invoke the appropriate business logic corresponding to the incoming request
 Choose the appropriate kind of response to return
 An action doesn’t need to perform all of these actions, but at the very least
it must choose the kind of response to return
Action methods - Parameters
 As we saw earlier, action methods can have parameters
 These parameters could be of complex or reference type such as
OrderModel, but
 They can also be primitive types, such as string or int
Action methods – return type
 An action method can return any data type, but in a typical MVC
application, action methods generally return
 a ViewResult that the MvcMiddleware will use to generate an HTML response,
or
 a RedirectResult, which indicates the user should be redirected to a different
page in your application
 Both are subtypes of ActionResult
 ActionResult is an abstract class that implements the IActionResult
interface
Action methods – return type
 For either case (when ViewResult or RedirectResult is returned) you can
also use the IActionResult as return type
 However, if your action method returns more than one type, the return
type must be IActionResult
 In the validation example in slide 6, the method returns either a ViewResult or
RedirectResult
IActionResult
 In addition to ViewResult and RedirectResult, ASP.NET Core has other
types of IActionResult:
 RedirectToRouteResult
 FileResult
 ContentResult
 StatusCodeResult
 NotFoundResult
IActionResult
 If controller inherits from Controller class:
 You can use a number of helper methods to generate response
 For example: View() method
 View() method has several overloads:
 View()
 View(model)
 View(name)
 Name is the name of a specified view
 View (name, model)
Conventions for controllers
 MVC controllers are discovered and used by the MvcMiddleware as long
as they are instantiable (they have a public constructor, aren’t static, and
aren’t abstract) and either:
 Have a name ending in “Controller,” for example HomeController
 Inherit from the Controller or ControllerBase class (or a class that inherits from
these)
 It’s often a good idea to use the Controller class, given that it contains a
number of helper methods for returning results
 Another common convention is to place all your controller files in a
Controllers subfolder in your project

More Related Content

Similar to Chapter4.pptx

ASP.NET MVC Controllers & Actions
ASP.NET MVC Controllers & ActionsASP.NET MVC Controllers & Actions
ASP.NET MVC Controllers & Actionsonsela
 
Sitecore MVC (London User Group, April 29th 2014)
Sitecore MVC (London User Group, April 29th 2014)Sitecore MVC (London User Group, April 29th 2014)
Sitecore MVC (London User Group, April 29th 2014)Ruud van Falier
 
Controllers & actions
Controllers & actionsControllers & actions
Controllers & actionsEyal Vardi
 
Using a model view-view model architecture for iOS apps
Using a model view-view model architecture for iOS appsUsing a model view-view model architecture for iOS apps
Using a model view-view model architecture for iOS appsallanh0526
 
LearningMVCWithLINQToSQL
LearningMVCWithLINQToSQLLearningMVCWithLINQToSQL
LearningMVCWithLINQToSQLAkhil Mittal
 
Mvc4 crud operations.-kemuning senja
Mvc4 crud operations.-kemuning senjaMvc4 crud operations.-kemuning senja
Mvc4 crud operations.-kemuning senjaalifha12
 
Model view controller (mvc)
Model view controller (mvc)Model view controller (mvc)
Model view controller (mvc)M Ahsan Khan
 
ASP.NET - Building Web Application..in the right way!
ASP.NET - Building Web Application..in the right way!ASP.NET - Building Web Application..in the right way!
ASP.NET - Building Web Application..in the right way!Fioriela Bego
 
ASP.NET - Building Web Application..in the right way!
ASP.NET - Building Web Application..in the right way!ASP.NET - Building Web Application..in the right way!
ASP.NET - Building Web Application..in the right way!Commit Software Sh.p.k.
 
Repository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkRepository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkAkhil Mittal
 
Introduction To Mvc
Introduction To MvcIntroduction To Mvc
Introduction To MvcVolkan Uzun
 
MVC ppt presentation
MVC ppt presentationMVC ppt presentation
MVC ppt presentationBhavin Shah
 
Sitecore MVC (User Group Conference, May 23rd 2014)
Sitecore MVC (User Group Conference, May 23rd 2014)Sitecore MVC (User Group Conference, May 23rd 2014)
Sitecore MVC (User Group Conference, May 23rd 2014)Ruud van Falier
 
Tightly coupled view (model bounded view)
Tightly coupled view (model bounded view)Tightly coupled view (model bounded view)
Tightly coupled view (model bounded view)IT PROGRAMMING WORLD
 

Similar to Chapter4.pptx (20)

CodeIgniter 101 Tutorial
CodeIgniter 101 TutorialCodeIgniter 101 Tutorial
CodeIgniter 101 Tutorial
 
ASP.NET MVC Controllers & Actions
ASP.NET MVC Controllers & ActionsASP.NET MVC Controllers & Actions
ASP.NET MVC Controllers & Actions
 
Sitecore MVC (London User Group, April 29th 2014)
Sitecore MVC (London User Group, April 29th 2014)Sitecore MVC (London User Group, April 29th 2014)
Sitecore MVC (London User Group, April 29th 2014)
 
MVC Training Part 2
MVC Training Part 2MVC Training Part 2
MVC Training Part 2
 
Spring Web MVC
Spring Web MVCSpring Web MVC
Spring Web MVC
 
Controllers & actions
Controllers & actionsControllers & actions
Controllers & actions
 
Using a model view-view model architecture for iOS apps
Using a model view-view model architecture for iOS appsUsing a model view-view model architecture for iOS apps
Using a model view-view model architecture for iOS apps
 
LearningMVCWithLINQToSQL
LearningMVCWithLINQToSQLLearningMVCWithLINQToSQL
LearningMVCWithLINQToSQL
 
MVC 4
MVC 4MVC 4
MVC 4
 
Mvc4 crud operations.-kemuning senja
Mvc4 crud operations.-kemuning senjaMvc4 crud operations.-kemuning senja
Mvc4 crud operations.-kemuning senja
 
Model view controller (mvc)
Model view controller (mvc)Model view controller (mvc)
Model view controller (mvc)
 
ASP.NET - Building Web Application..in the right way!
ASP.NET - Building Web Application..in the right way!ASP.NET - Building Web Application..in the right way!
ASP.NET - Building Web Application..in the right way!
 
ASP.NET - Building Web Application..in the right way!
ASP.NET - Building Web Application..in the right way!ASP.NET - Building Web Application..in the right way!
ASP.NET - Building Web Application..in the right way!
 
Repository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkRepository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity Framework
 
Introduction To Mvc
Introduction To MvcIntroduction To Mvc
Introduction To Mvc
 
ASP.NET-MVC-Part-1.ppt
ASP.NET-MVC-Part-1.pptASP.NET-MVC-Part-1.ppt
ASP.NET-MVC-Part-1.ppt
 
Asp.Net MVC Intro
Asp.Net MVC IntroAsp.Net MVC Intro
Asp.Net MVC Intro
 
MVC ppt presentation
MVC ppt presentationMVC ppt presentation
MVC ppt presentation
 
Sitecore MVC (User Group Conference, May 23rd 2014)
Sitecore MVC (User Group Conference, May 23rd 2014)Sitecore MVC (User Group Conference, May 23rd 2014)
Sitecore MVC (User Group Conference, May 23rd 2014)
 
Tightly coupled view (model bounded view)
Tightly coupled view (model bounded view)Tightly coupled view (model bounded view)
Tightly coupled view (model bounded view)
 

Recently uploaded

Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...Jack DiGiovanna
 
Dubai Call Girls Wifey O52&786472 Call Girls Dubai
Dubai Call Girls Wifey O52&786472 Call Girls DubaiDubai Call Girls Wifey O52&786472 Call Girls Dubai
Dubai Call Girls Wifey O52&786472 Call Girls Dubaihf8803863
 
Unveiling Insights: The Role of a Data Analyst
Unveiling Insights: The Role of a Data AnalystUnveiling Insights: The Role of a Data Analyst
Unveiling Insights: The Role of a Data AnalystSamantha Rae Coolbeth
 
PKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptxPKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptxPramod Kumar Srivastava
 
Log Analysis using OSSEC sasoasasasas.pptx
Log Analysis using OSSEC sasoasasasas.pptxLog Analysis using OSSEC sasoasasasas.pptx
Log Analysis using OSSEC sasoasasasas.pptxJohnnyPlasten
 
Industrialised data - the key to AI success.pdf
Industrialised data - the key to AI success.pdfIndustrialised data - the key to AI success.pdf
Industrialised data - the key to AI success.pdfLars Albertsson
 
Digi Khata Problem along complete plan.pptx
Digi Khata Problem along complete plan.pptxDigi Khata Problem along complete plan.pptx
Digi Khata Problem along complete plan.pptxTanveerAhmed817946
 
{Pooja: 9892124323 } Call Girl in Mumbai | Jas Kaur Rate 4500 Free Hotel Del...
{Pooja:  9892124323 } Call Girl in Mumbai | Jas Kaur Rate 4500 Free Hotel Del...{Pooja:  9892124323 } Call Girl in Mumbai | Jas Kaur Rate 4500 Free Hotel Del...
{Pooja: 9892124323 } Call Girl in Mumbai | Jas Kaur Rate 4500 Free Hotel Del...Pooja Nehwal
 
Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...soniya singh
 
Full night 🥵 Call Girls Delhi New Friends Colony {9711199171} Sanya Reddy ✌️o...
Full night 🥵 Call Girls Delhi New Friends Colony {9711199171} Sanya Reddy ✌️o...Full night 🥵 Call Girls Delhi New Friends Colony {9711199171} Sanya Reddy ✌️o...
Full night 🥵 Call Girls Delhi New Friends Colony {9711199171} Sanya Reddy ✌️o...shivangimorya083
 
Call Girls In Mahipalpur O9654467111 Escorts Service
Call Girls In Mahipalpur O9654467111  Escorts ServiceCall Girls In Mahipalpur O9654467111  Escorts Service
Call Girls In Mahipalpur O9654467111 Escorts ServiceSapana Sha
 
Predicting Employee Churn: A Data-Driven Approach Project Presentation
Predicting Employee Churn: A Data-Driven Approach Project PresentationPredicting Employee Churn: A Data-Driven Approach Project Presentation
Predicting Employee Churn: A Data-Driven Approach Project PresentationBoston Institute of Analytics
 
B2 Creative Industry Response Evaluation.docx
B2 Creative Industry Response Evaluation.docxB2 Creative Industry Response Evaluation.docx
B2 Creative Industry Response Evaluation.docxStephen266013
 
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Callshivangimorya083
 
定制英国白金汉大学毕业证(UCB毕业证书) 成绩单原版一比一
定制英国白金汉大学毕业证(UCB毕业证书)																			成绩单原版一比一定制英国白金汉大学毕业证(UCB毕业证书)																			成绩单原版一比一
定制英国白金汉大学毕业证(UCB毕业证书) 成绩单原版一比一ffjhghh
 
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdfKantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdfSocial Samosa
 
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130Suhani Kapoor
 

Recently uploaded (20)

Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
 
Dubai Call Girls Wifey O52&786472 Call Girls Dubai
Dubai Call Girls Wifey O52&786472 Call Girls DubaiDubai Call Girls Wifey O52&786472 Call Girls Dubai
Dubai Call Girls Wifey O52&786472 Call Girls Dubai
 
Unveiling Insights: The Role of a Data Analyst
Unveiling Insights: The Role of a Data AnalystUnveiling Insights: The Role of a Data Analyst
Unveiling Insights: The Role of a Data Analyst
 
PKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptxPKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptx
 
Log Analysis using OSSEC sasoasasasas.pptx
Log Analysis using OSSEC sasoasasasas.pptxLog Analysis using OSSEC sasoasasasas.pptx
Log Analysis using OSSEC sasoasasasas.pptx
 
Industrialised data - the key to AI success.pdf
Industrialised data - the key to AI success.pdfIndustrialised data - the key to AI success.pdf
Industrialised data - the key to AI success.pdf
 
Digi Khata Problem along complete plan.pptx
Digi Khata Problem along complete plan.pptxDigi Khata Problem along complete plan.pptx
Digi Khata Problem along complete plan.pptx
 
{Pooja: 9892124323 } Call Girl in Mumbai | Jas Kaur Rate 4500 Free Hotel Del...
{Pooja:  9892124323 } Call Girl in Mumbai | Jas Kaur Rate 4500 Free Hotel Del...{Pooja:  9892124323 } Call Girl in Mumbai | Jas Kaur Rate 4500 Free Hotel Del...
{Pooja: 9892124323 } Call Girl in Mumbai | Jas Kaur Rate 4500 Free Hotel Del...
 
Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝
 
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...
 
VIP Call Girls Service Charbagh { Lucknow Call Girls Service 9548273370 } Boo...
VIP Call Girls Service Charbagh { Lucknow Call Girls Service 9548273370 } Boo...VIP Call Girls Service Charbagh { Lucknow Call Girls Service 9548273370 } Boo...
VIP Call Girls Service Charbagh { Lucknow Call Girls Service 9548273370 } Boo...
 
Full night 🥵 Call Girls Delhi New Friends Colony {9711199171} Sanya Reddy ✌️o...
Full night 🥵 Call Girls Delhi New Friends Colony {9711199171} Sanya Reddy ✌️o...Full night 🥵 Call Girls Delhi New Friends Colony {9711199171} Sanya Reddy ✌️o...
Full night 🥵 Call Girls Delhi New Friends Colony {9711199171} Sanya Reddy ✌️o...
 
Call Girls In Mahipalpur O9654467111 Escorts Service
Call Girls In Mahipalpur O9654467111  Escorts ServiceCall Girls In Mahipalpur O9654467111  Escorts Service
Call Girls In Mahipalpur O9654467111 Escorts Service
 
Predicting Employee Churn: A Data-Driven Approach Project Presentation
Predicting Employee Churn: A Data-Driven Approach Project PresentationPredicting Employee Churn: A Data-Driven Approach Project Presentation
Predicting Employee Churn: A Data-Driven Approach Project Presentation
 
B2 Creative Industry Response Evaluation.docx
B2 Creative Industry Response Evaluation.docxB2 Creative Industry Response Evaluation.docx
B2 Creative Industry Response Evaluation.docx
 
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
 
定制英国白金汉大学毕业证(UCB毕业证书) 成绩单原版一比一
定制英国白金汉大学毕业证(UCB毕业证书)																			成绩单原版一比一定制英国白金汉大学毕业证(UCB毕业证书)																			成绩单原版一比一
定制英国白金汉大学毕业证(UCB毕业证书) 成绩单原版一比一
 
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in Kishangarh
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in  KishangarhDelhi 99530 vip 56974 Genuine Escort Service Call Girls in  Kishangarh
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in Kishangarh
 
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdfKantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
 
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
 

Chapter4.pptx

  • 2. Controller  This is what we have learned about ‘controller’ so far:  It is one of the three MVC components  It is a C# class that contains action methods  An action method is a method that runs in response to a request  It is the entry point when a HTTP request is received  Depending on the request, the controller may get the requested data from the model or update the model data  Then the controller selects a View to display, passing data to it  In this chapter, we will have a closer look at controllers
  • 3. Request, controller and binding model  The first step when the MvcMiddleware receives a request is routing the request to an appropriate controller  Routing takes the path of the request, and maps it to one of the actions in the controller  Once an action is selected, if the request has data, a binding model is generated  A binding model is an object that acts as a “container” for the data provided in a request  Data could be part of the URL, query string, headers, or form fields
  • 4. Request, controller and binding model  Some action methods do not have parameters, for example a request to display the home page, like the one below: public IActionResult Index() { }  This action method does not use a binding model, if one is created  However, some action methods have parameters; they are used to receive data contained in the request
  • 5. Request, controller and binding model  When ‘Submit Order’ is clicked, the request is mapped to this action of HomeController, because of the HTTPPost attribute  An object (of the OrderModel type) is created using the data entered in the Index view (customer, item, price, quantity). This is the binding model  This object (the binding model) is passed to the action method. So, the parameter ‘model’ of the Index method holds the binding model [HTTPPost] public IActionResult Index(OrderModel model) { ViewBag.AmtDue = model.CalculateAmountDue(); return View(); }
  • 6. Validation  Next, the action method: 1. Validates the data contained in the binding model 2. Invokes the appropriate actions on the application model 3. Generates a response based on the output from the application model  Below is an illustration of Step 1, validation: public IActionResult Search(OrderModel model) { if(ModelState.IsValid) { …… return View(); } return Redirect("/") }  ModelState is a property inherited from the Controller class
  • 7. Using the application model  Step 2 is illustrated below, from the Order Processing example: ViewBag.AmtDue = model.CalculateAmountDue();  In this case, our application model consists of a single class, OrderModel and controller is invoking a method of this class
  • 8. Generating response  Step 3, the action method selects the view template and passes the view model to it, if applicable  View model is an object required by the view to generate a UI  View model can be one of business logic classes, for example Order class, or  It can be a class created specifically to represent the structure of the data needed by a view  We will look at these types of models in the future
  • 9. Action methods  Any public method on a controller acts as an action method  To review, the responsibility of an action method is generally threefold:  Confirm the incoming request is valid  Invoke the appropriate business logic corresponding to the incoming request  Choose the appropriate kind of response to return  An action doesn’t need to perform all of these actions, but at the very least it must choose the kind of response to return
  • 10. Action methods - Parameters  As we saw earlier, action methods can have parameters  These parameters could be of complex or reference type such as OrderModel, but  They can also be primitive types, such as string or int
  • 11. Action methods – return type  An action method can return any data type, but in a typical MVC application, action methods generally return  a ViewResult that the MvcMiddleware will use to generate an HTML response, or  a RedirectResult, which indicates the user should be redirected to a different page in your application  Both are subtypes of ActionResult  ActionResult is an abstract class that implements the IActionResult interface
  • 12. Action methods – return type  For either case (when ViewResult or RedirectResult is returned) you can also use the IActionResult as return type  However, if your action method returns more than one type, the return type must be IActionResult  In the validation example in slide 6, the method returns either a ViewResult or RedirectResult
  • 13. IActionResult  In addition to ViewResult and RedirectResult, ASP.NET Core has other types of IActionResult:  RedirectToRouteResult  FileResult  ContentResult  StatusCodeResult  NotFoundResult
  • 14. IActionResult  If controller inherits from Controller class:  You can use a number of helper methods to generate response  For example: View() method  View() method has several overloads:  View()  View(model)  View(name)  Name is the name of a specified view  View (name, model)
  • 15. Conventions for controllers  MVC controllers are discovered and used by the MvcMiddleware as long as they are instantiable (they have a public constructor, aren’t static, and aren’t abstract) and either:  Have a name ending in “Controller,” for example HomeController  Inherit from the Controller or ControllerBase class (or a class that inherits from these)  It’s often a good idea to use the Controller class, given that it contains a number of helper methods for returning results  Another common convention is to place all your controller files in a Controllers subfolder in your project