Изменить данные в DataTable с помощью Выбрать из выпадающего списка - PullRequest
0 голосов
/ 01 января 2019

У меня есть представление с таблицей данных, и я хочу изменять данные каждый раз, когда выбираю категорию из раскрывающегося списка.

Я хочу отображать только альбомы из выбранной категории иливсе альбомы из всех категорий, используя Ajax и jQuery.Выпадающий список должен быть расположен над таблицей.

Вот мой код:

@using System.Collections.Generic;
@using CakeStore.App.Areas.Admin.Models.Albums;
@using CakeStore.App.Services.Contracts;
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

@inject IAlbumService AlbumService


@{ ViewData["Title"] = "Category Albums";
    Layout = "~/Areas/Admin/Views/Shared/_AdminLayout.cshtml";
    var albums = ViewBag.CategoryAlbums as List<AlbumTableViewModel>;

}

<h1 class="text-center text-header-page">Category Albums</h1>
<hr class="hr-admin-divider" />
<div class="form-group">
    <a class="btn button-black-white d-flex justify-content-left" href="/Admin/Albums/Create">Create</a>
</div>
<hr class="hr-admin-divider" />

<div class="d-flex">

    <table class="table table-striped table-hover" id="myTable">
        <tr>
            <th>#</th>
            <th>Name</th>
            <th>Category</th>
            <th></th>
            <th></th>
            <th></th>
        </tr>
        @for (int i = 0; i < albums.Count(); i++) {

            <tr>
                <td class="col-md-1">@albums[i].Id</td>
                <td class="col-md-3">@albums[i].Name</td>
                <td class="col-md-2">@albums[i].Category</td>
                <td><a class="btn button-table-edit" href="/Admin/Albums/Edit?id=@albums[i].Id">EDIT</a></td>
                <td><a class="btn button-table-delete d-flex justify-content-right" href="/Admin/Albums/Delete?id=@albums[i].Id">DELETE</a></td>
                <td><a class="btn button-table-view d-flex justify-content-right" href="/Admin/Products/CategoryAlbums?id=@albums[i].Id">PRODUCTS</a></td>
            </tr>
        }
    </table>
</div>
<div class="row d-flex align-items-end flex-column" style="font-size:12px">
    <a class="btn-link pull-right col-lg-2" asp-controller="Categories" asp-action="Category">Back to Categories</a>
</div>


@section Scripts {
    <partial name="_ValidationScriptsPartial" />
}

1 Ответ

0 голосов
/ 02 января 2019

Вы можете использовать частичное представление, я сделал демо, вы можете обратиться к нему

Используйте ajax для вызова метода GetCityList, чтобы получить данные, соответствующие переданному countryId.

<div class="form-group">
<label class="col-form-label">Country</label>
<select class="form-control" asp-items="@ViewBag.Country" id="selectlist">
    <option>All</option>
</select>
</div>

<div class="form-group" id="cityListWrapper">
<partial name="_CityListPartial" model="@ViewBag.City" />
</div>

@section Scripts
{
<script type="text/javascript">
    $("#selectlist").change(function () {
        var countryId = $("#selectlist").val();
        $.ajax
            ({
                type: "GET",
                url: "/Countries/GetCityList?CountryId="+countryId,
                success: function (result) {
                    $("#cityListWrapper").html(result)
                }
            });

    });
</script>
}

Первоначальный рендеринг основного представления, показывать все альбомы, когда он не выбран

 public async Task<IActionResult> Index()
    {
        ViewBag.Country = new SelectList(_context.Country, "Id", "CountryName");
        ViewBag.City = _context.City.ToList();

        return View();
    }

Действие GetCityList, отображать частичное представление, используя инструкцию, которая возвращает разные значения

 [HttpGet]
    public async Task<IActionResult> GetCityList(int? countryId)
    {
        if (countryId == null)
        {
            var CityList = await _context.City.ToListAsync();
            return PartialView("_CityListPartial", CityList);
        }
        var Cities =await _context.City.Where(c => c.Country.Id == countryId).ToListAsync();
        return PartialView("_CityListPartial", Cities);
    }

Как это работает

enter image description here

...