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:
- Add a search parameter to the GetQuestions method:
[HttpGet]
public IEnumerable<QuestionGetManyResponse>
GetQuestions(string search)
{
var questions = _dataRepository.GetQuestions();
return questions;
}
- 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.
- 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.
- Let's stop the app running by pressing Shift + F5.
- 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.
- 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);
}
}
- 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.
- 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.