Как сделать сортировку на странице в. net основном приложении - PullRequest
0 голосов
/ 19 марта 2020

Извините, если я не могу написать такой вопрос, пожалуйста, прости меня. Я учусь. net ядро. Я хочу реализовать сортировку в моем проекте, но получаю сообщение об ошибке:

«IQueryable» не содержит определения для «AsNoTracking» и нет доступного метода расширения «AsNoTracking», принимающего первый аргумент типа «IQueryable» может быть найдено (вам не хватает директивы using или ссылки на сборку?)

appsettings. json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "connectionstring": "Server=(localdb)\\MSSQLLocalDB;Database=StudentDB;Trusted_Connection=True;MultipleActiveResultSets=true"    
  }
}

Startup.cs

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContextPool<AppDBContext>(option => option.UseSqlServer(Configuration.GetConnectionString("connectionstring")));          
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

AppDBContext.cs

namespace WebApplication1.Models
{
    public class AppDBContext:DbContext
    {

        public AppDBContext(DbContextOptions<AppDBContext> options)
            :base(options)
        {

        }
        public DbSet<Student> studentlist { get; set; }
    }
}

Student.cs

namespace WebApplication1.Models
{
    public class Student
    {
        public int Id { get; set; }
        public string StudentName { get; set; }
        public string StdLName { get; set; }
        public DateTime? year { get; set; }
    }
}

HomeController

 public class HomeController : Controller
    {
        private AppDBContext _context;

        private readonly IConfiguration _Configuration;

        public HomeController( AppDBContext context, IConfiguration configuration)
        {
            _context = context;
            _Configuration = configuration;
        }

        public async Task<IActionResult> Index(string sortOrder)
        {
            ViewData["NameSortParm"] = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
            ViewData["DateSortParm"] = sortOrder == "Date" ? "date_desc" : "Date";

            var students = from s in _context.studentlist
                           select s;
            switch (sortOrder)
            {
                case "name_desc":
                    students = students.OrderByDescending(s => s.StudentName);
                    break;
                case "Date":
                    students = students.OrderBy(s => s.year);
                    break;
                case "date_desc":
                    students = students.OrderByDescending(s => s.year);
                    break;
                default:
                    students = students.OrderBy(s => s.StudentName);
                    break;
            }
            return View(await students.AsNoTracking.ToListAsync());
        }

Просмотр индекса

<table class="table">
    <thead>
        <tr>
            <th>
                <a asp-action="Index" asp-route-sortOrder="@ViewData["NameSortParm"]">@Html.DisplayNameFor(model => model.StudentName)</a>
            </th>

            <th>
                <a asp-action="Index" asp-route-sortOrder="@ViewData["DateSortParm"]">@Html.DisplayNameFor(model => model.year)</a>
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.StudentName)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.year)
                </td>

            </tr>
        }
    </tbody>
</table>

1 Ответ

0 голосов
/ 19 марта 2020

Замените

return View(await students.AsNoTracking.ToListAsync());

на

return View(await students.AsNoTracking().ToListAsync());

на вашем HomeController. Когда вы набираете код VS / VS, Intellisense должен немедленно сообщить вам, что AsNoTracking является методом, поэтому вы должны вызывать его с помощью ()

...