How to pass parameters to action methods in ASP.NET Core MVC
ASP.Internet Core is a cross-system, open up supply, lean, speedy, and modular framework for making high-effectiveness website apps. There are a range of methods in which you can pass parameters to motion methods in ASP.Internet Core MVC. You can pass them via a URL, a question string, a request header, a request human body, or even a sort. This post talks about all of these methods, and illustrates them with code illustrations.
To perform with the code illustrations offered in this post, you should really have Visible Studio 2019 set up in your process. If you don’t currently have a copy, you can down load Visible Studio 2019 here.
Generate an ASP.Internet Core MVC job in Visible Studio 2019
To start with off, let us make an ASP.Internet Core job in Visible Studio 2019. Assuming Visible Studio 2019 is set up in your process, adhere to the ways outlined under to make a new ASP.Internet Core job in Visible Studio.
- Start the Visible Studio IDE.
- Click on on “Create new job.”
- In the “Create new project” window, select “ASP.Internet Core Net Application” from the record of templates shown.
- Click on Following.
- In the “Configure your new project” window, specify the title and locale for the new job.
- Optionally test the “Place answer and job in the very same directory” test box, depending on your tastes.
- Click on Generate.
- In the “Create a New ASP.Internet Core Net Application” window shown following, select .Internet Core as the runtime and ASP.Internet Core 3.1 (or later) from the fall-down record at the top.
- Select “Web Application (Product-Perspective-Controller)” as the job template to make a new ASP.Internet Core MVC software.
- Make certain that the test boxes “Enable Docker Support” and “Configure for HTTPS” are unchecked as we will not be using these capabilities here.
- Make certain that Authentication is established to “No Authentication” as we will not be using authentication both.
- Click on Generate.
Pursuing these ways should really make a new ASP.Internet Core MVC job in Visible Studio 2019. We’ll use this job in the sections under to illustrate the a variety of methods of passing parameters to motion methods in ASP.Internet Core 3.1.
Generate an AuthorRepository class in ASP.Internet Core MVC
In this instance we’ll be using a repository class — the motion methods in the controller will interact with the methods of the repository class for CRUD operations. We’ll very first make a product class named Creator with minimum properties for the sake of simplicity as shown in the code snippet presented under.
community class Creator
community int Id get established
community string FirstName get established
community string LastName get established
The AuthorRepository class contains methods for retrieving situations of the Creator class from a generic record as effectively as for including new situations of the Creator class to the generic record. The GetAuthors approach returns a web page of information, the web page range becoming passed to it as an argument.
community class AuthorRepository
{
Checklistauthors = new Checklist ()
new Creator
Id = 1,
FirstName = "Joydip",
LastName = "Kanjilal"
,
new Creator
Id = 2,
FirstName = "Steve",
LastName = "Smith"
community Creator GetAuthor(int id)
return authors.FirstOrDefault(a => a.Id == id)
community ChecklistGetAuthors(int pageNumber = 1)
int pageSize = 10
int skip = pageSize * (pageNumber - 1)
if (authors.Depend < pageSize)
pageSize = authors.Depend
return authors
.Skip(skip)
.Just take(pageSize).ToList()
community bool Help save(Creator author)
var final result = authors.In which(a => a.Id == author.Id)
if (final result != null)
if (final result.Depend() == )
authors.Increase(author)
return real
return untrue
}
Pass parameters via the URL in ASP.Internet Core MVC
One particular of the easiest and most straightforward methods to pass parameters to an motion approach is passing it via the URL. The adhering to code snippet illustrates how you can pass parameters in the URL.
[HttpGet]
[Route("Default/GetAuthor/authorId:int")]
community IActionResult GetAuthor(int authorId)
var information = authorRepository.GetAuthor(authorId)
return Perspective(information)
The URL to the endpoint is:
GET: http://localhost:8061/Default/GetAuthor/1
Pass parameters via question string in ASP.Internet Core MVC
Passing parameters in the question string is one more selection. It doesn’t require modifying the routing info and therefore is backwards suitable. Think about the adhering to code snippet that illustrates how you can pass parameters via question strings in an motion approach.
[HttpGet]
[Route("Default/GetAuthors/pageNumber:int")]
community IActionResult GetAuthors([FromQuery
(Identify = "pageNumber")] int pageNumber = 1)
var information = authorRepository.GetAuthors(pageNumber)
return Okay(information)
Right here is the URL to accessibility this endpoint:
GET: http://localhost:8061/Default/GetAuthors?pageNumber=1
The GetAuthors approach accepts the web page range as an argument sent to it via question string. Notice that pageNumber is an optional parameter — if no parameter is passed to this approach, then the web page range would be interpreted as 1. The approach returns the author information for the specified web page. In our instance, if there are 100 author information in the information store and the web page range is 3, this approach would return information 31 to 40. (Notice that the range of authors per web page is tricky coded it is specified as 10 in the AuthorRepository class.)
Pass parameters via request header in ASP.Internet Core MVC
The request header is nonetheless one more selection for passing parameters to your motion methods. A widespread use situation for this is passing qualifications or any other top secret information over the wire. The adhering to code snippet illustrates an motion approach that accepts a credit rating card range as a parameter and returns real if the credit rating card range is valid.
[HttpGet]
[Route("Default/IsCreditCardValid/creditCardNumber")]
community IActionResult IsCreditCardValid([FromHeader] string creditCardNumber)
" +
"(?5[1-5][-nine]fourteen)
For the sake of simplicity, the IsCreditCardValid motion approach validates Visa, MasterCard, and Amex credit rating playing cards only. You can extend the IsCreditCardValid approach to validate other card forms. Considering the fact that the credit rating card range should really be passed securely, using the request header is a fantastic preference here. Figure 1 shows how you can specify your credit rating card range as a parameter via request header.
Figure 1.
Pass parameters via request human body in ASP.Internet Core MVC
You will frequently need to pass parameters via the request human body when you are executing insert or update operations. The adhering to code snippet illustrates how you can pass an occasion of the Creator class via the human body of the request.
[HttpPost]
[Route("Default/Insert")]
community IActionResult Insert([FromBody] Creator author)
return Okay(authorRepository.Help save(author))
Figure 2 shows how you can specify the information to be inserted in the request human body.
Figure 2.
Total supply code of our DefaultController class
The entire code of the DefaultController class is offered under for your reference.
public class DefaultController : Controller
non-public readonly AuthorRepository authorRepository =
new AuthorRepository()
[HttpGet]
[Route("Default/GetAuthor/authorId:int")]
community IActionResult GetAuthor(int authorId)
var information = authorRepository.GetAuthor(authorId)
return Okay(information)
[HttpGet]
[Route("Default/GetAuthors/pageNumber:int")]
community IActionResult GetAuthors([FromQuery
(Identify = "pageNumber")] int pageNumber = 1)
var information = authorRepository.GetAuthors(pageNumber)
return Okay(information)
[HttpGet]
[Route("Default/IsCreditCardValid/creditCardNumber")]
community IActionResult IsCreditCardValid
([FromHeader] string creditCardNumber)
" +
"(?3[47][-nine]13)
[HttpPost]
[Route("Default/Insert")]
community IActionResult Insert([FromBody] Creator author)
return Okay(authorRepository.Help save(author))
Lastly, you can also pass parameters via a sort. A sort is frequently utilized when you would like to add a file. You would need to take gain of the IFormFile interface in this situation.
How to do a lot more in ASP.Internet Core:
Copyright © 2020 IDG Communications, Inc.