搜索字符串时剃须刀页面出错

时间:2020-11-09 06:17:47

标签: asp.net-core web razor-pages

虽然在asp .net核心中了解剃须刀页面时,我遇到了一个错误,但添加此部分是为了搜索网页上的字符串,但结果没有任何改变。 我该怎么办? 请帮助我

['ahmed', '10', 'M']
['moahmed','20','N/A']
['ramy','N/A','N/A']

结果: enter image description here

我期望的结果是: enter image description here

2 个答案:

答案 0 :(得分:0)

使用以下代码更改OnGetAsymc方法

public async Task OnGetAsync()
{
    var movies = from m in _context.Movie
                 where string.IsNullOrEmpty(SearchString) || m.Title.Contains(SearchString)
                 select m;
    //if (!string.IsNullOrEmpty(SearchString))
    //{
    //    movies = movies.Where(s => s.Title.Contains(SearchString));
    //}
    Movie = movies.ToListAsync();//await _context.Movie.ToListAsync();
}

答案 1 :(得分:0)

根据您的描述,我想您可能没有为路由页面设置正确的路由,并且OnGetAsync方法中的某些逻辑是错误的。

首先,如果要在路径中将SearchString绑定为友好网址,建议您在剃须刀页面中将其设置为以下内容。像下面一样

@page "{SearchString}"

然后,您可以使用https://localhost:xxxx/Movies/Ghost访问该页面,它将自动将Ghost绑定到SearchString。

此外,我发现您已经在if条件之后重新查询了Movie。这将使搜索结果不符合SearchString。

像下面这样:

public async Task OnGetAsync()
{
    var movies = from m in _context.Movie
                 select m;
    if (!string.IsNullOrEmpty(SearchString))
    {
        movies = movies.Where(s => s.Title.Contains(SearchString));
        Movie = await movies.ToListAsync()
    }else{
       Movie = await _context.Movie.ToListAsync();
    }

}

更多细节,您可以参考下面的测试演示。

剃刀页面:

由于我不知道您的电影剃须刀页面的组成,因此我创建了一个简单的页面。

@page "{SearchString}"
@model RazorPageRelated.MoviesModel
@{
}



<div class="text-center">
 
    @foreach (var item in Model.Movie)
    {
        <p>@item.Name</p><br/>
    }

</div>

型号代码:

public class MoviesModel : PageModel
{

    public List<Movie> Movie { get; set; }

    public IList<Movie> Context = new List<Movie>() {
          new Movie{ Id=1, Name="When Harry"},
          new Movie{ Id=1, Name="Ghost22222"},
          new Movie{ Id=1, Name="Ghost11111"},
        };


    [BindProperty(SupportsGet = true)]
    public string SearchString { get; set; }
    public void OnGet()
    {
        if (!string.IsNullOrEmpty(SearchString))
        {
            Movie = Context.Where(s => s.Name.Contains(SearchString)).ToList();
        }
        else
        {
            Movie = Context.ToList();
        }
      
    }
}

结果:

enter image description here

相关问题