2021年3月25日星期四

Searching through a list on mvc razor pages

I have the following Model:

 public class Photo      {          public string Id { get; set; }          public List<string> Hashtag { get; set; }          public string PhotoUrl { get; set; }          public string SearchString { get; set; }      }  

My view looks like this:

@model PhotoSearch.Models.Photo[]  <div class="text-center">      <p>Search.</p>      <form>          <p>              Title: <input type="text" asp-for="SearchString" />              <input type="submit" value="Filter" />          </p>      </form>  </div>      <h2>Photos</h2>  @{      foreach (var photo in @Model)      {          <table>              <tr>                  <th>URL</th>                  <th>Hashtags</th>              </tr>              <tr>                  <th>@photo.PhotoUrl %</th>                  <th>@String.Join(", ", @photo.Hashtag.ToArray());</th>              </tr>          </table>      }  }  

I am getting a list of photos which are initially in Json format from an API, and then deserializing them into the above object:

using (HttpClient client = new HttpClient())                  {                      using (HttpResponseMessage response = await client.GetAsync(baseUrl))                      {                          using (HttpContent content = response.Content)                          {                                        string data = await content.ReadAsStringAsync();                                if (data != null)                              {                                  var photoList = JsonConvert.DeserializeObject<Photo[]>(data);                                    if (!String.IsNullOrEmpty(searchString))                                  {                                      var filteredList = photoList.Where(v => v.Hashtags.Contains(searchString));                                      return View(filteredList);                                  }                                    return View(photoList);                              }                          }                      }                  }  

I have the search form at the top as I want users to be able to enter in a list of hashtags, which will filter the results as if there's a SearchString populated, a different view will show with just the filtered photos. My issue is that SearchString is a property for Photo but not the Photo[] that's being used in the view. If I use a foreach the search box just appears several times. Is there a simpler way I can filter through the photos?

https://stackoverflow.com/questions/66795746/searching-through-a-list-on-mvc-razor-pages March 25, 2021 at 04:34PM

没有评论:

发表评论