Extending the GetQuestions action method for searching

We don't always want all of the questions though. Recall that our frontend had a search feature that returned questions that matched the search criteria. Let's extend our GetQuestions method to handle a search request:

  1. Add a search parameter to the GetQuestions method:
[HttpGet]
public IEnumerable<QuestionGetManyResponse>
GetQuestions(string search)
{
var questions = _dataRepository.GetQuestions();
return questions;
}
  1. Put a breakpoint on the statement that gets the questions from the repository and press F5 to run the app:

We'll see that the search parameter is null. Press F5 to let the app continue.

  1. With the breakpoint still in place, change the URL in the browser to end with questions?search=type:

This time the search parameter is set to the value of the search query parameter we put in the browser URL. This process is called model binding.

Model binding is a process in ASP.NET Core that maps data from HTTP requests to action method parameters. Data from query parameters is automatically mapped to action method parameters that have the same name. We'll see later in this section that model binding can also map data from the HTTP request body. So, a [FromQuery] attribute could be placed in front of the action method parameter to instruct ASP.NET Core to map only from the query parameter.
  1. Let's stop the app running by pressing Shift + F5.
  2. Let's branch our code on whether the search parameter contains a value and get and return all the questions if it doesn't:
[HttpGet]
public IEnumerable<QuestionGetManyResponse>
GetQuestions(string search)
{
if (string.IsNullOrEmpty(search))
{
return _dataRepository.GetQuestions();
}
else
{
// TODO - call data repository question search
}
}

If there is no search value, we get and return all the questions as we did before, but this time in a single statement. 

  1. Let's add a call to the data repository question search method if we have a search value:
[HttpGet]
public IEnumerable<QuestionGetManyResponse>
GetQuestions(string search)
{
if (string.IsNullOrEmpty(search))
{
return _dataRepository.GetQuestions();
}
else
{
return _dataRepository.GetQuestionsBySearch(search);
}
}
  1. Let's run the app and give this a try. All the questions will be returned in the browser when it opens up. Let's add a search query parameter with a value of type:

We'll see that the TypeScript question is returned as we would expect.

  1. Stop our app running by pressing Shift + F5 so that we can write more code for our next task.

We have started to take advantage of model binding in ASP.NET Core. We'll continue to use it throughout this chapter.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.1.156