Hi @Aaron soggi ,
First, as Bruce said, when transfer data from view to the controller uses the form, the element's name and the parameter name should be matched. And, since you will submit the form from the Index
page, there should be have a Index
action method.
Second, whether you are using the GetCity
view (assume there has this view) to display the city list or use the Index page?
If you are using a GetCity.cshtml page to display the city list, it is okey.
But, if you are using the Index view page to display the city list (filter result), in the GetCity
action method, you should also specify views when return data to view. Code like this:
Controller:
public class airQualityController : Controller
{
public async Task<IActionResult> Index(string cname)
{
var cities = await InnerGetCityAsync(cname);
return View(cities.results);
}
public async Task<ActionResult> GetCity(string cname)
{
try
{
var cities = await InnerGetCityAsync(cname);
return View("Views/airQuality/Index.cshtml", cities.results);
}
catch (Exception e)
{
return View(new { e.Message });
};
}
private async Task<RootModel> InnerGetCityAsync(string cname)
{
var client = new HttpClient();
client.BaseAddress = new Uri("https://docs.openaq.org/");
var results = new RootModel();
if (string.IsNullOrEmpty(cname))
{
results = await client.GetFromJsonAsync<RootModel>($"v2/cities").ConfigureAwait(false);
}
else
{
results = await client.GetFromJsonAsync<RootModel>($"v2/cities?city={cname}").ConfigureAwait(false);
}
return results;
}
}
Index.cshtml: Note: the controller name: airQuality
; Action name: GetCity
; Input element name: cname
; GetCity action parameter name: cname
@model IEnumerable<WebApplication2.Data.City>
@{
ViewData["Title"] = "airQuality Index";
}
<h1>IndexAsync</h1>
<div class="text-center">
<h1 class="display-4">OpenAQ Application</h1>
<form method="get" class="cityInput" asp-controller="airQuality" asp-action="GetCity">
<label for="fname">Enter a City:</label>
<input type="text" id="fname" placeholder="Type here" name="cname">
<input type="submit" value="Submit">
</form>
</div>
<p>
<a asp-action="Create">Create New</a>
</p>
<table class="table">
... use a table to display the page model.
</table>
The result like this:
In the above sample code, if you change the form tag (<form method="get" class="cityInput" asp-controller="airQuality" asp-action="GetCity">
) to <form method="get" class="cityInput">
, it will submit the form to the index action, and the result like this:
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Dillion