【问题标题】:How do I display object details from the model on bootstrap modal如何在引导模式上显示模型中的对象详细信息
【发布时间】:2019-12-13 05:20:23
【问题描述】:

我正在尝试从模型获取专辑详细信息以引导模式。我想单击每个专辑并显示每个特定专辑的艺术家和标题等相关信息。

当我使用 Asp.net Core 2.2 时,我尝试使用 asp-route-id="ID" 来映射对象,但问题是它正在显示所有页面详细信息。

这是我的模型

public class Album
{
    public int AlbumID { get; set; }
    public string Artist { get; set; }
    public int MusicID { get; set; }
    public virtual ICollection<Music> Music { get; set; }
}

音乐模型

    public class Music
{
    public int MusicID { get; set; }
    public string Title { get; set; }
    public int AlbumID { get; set; }
    public virtual Album Album { get; set; }
}

细节控制器 // GET: 专辑/详细信息/5

public async Task<IActionResult> Details(int? id) {
    if (id == null)
        {
            return NotFound();
        }

    var album = await _context.Albums.FirstOrDefaultAsync(m => m.AlbumID == id);
    if (album == null)
        {
            return NotFound();
        }

        return View(album);
}

下面是引导模式

<!-- Button trigger modal -->
<button type="button" asp-controller="Musics" asp-action="Details" asp-route-id="1" data-toggle="modal" data-target="#exampleModal">

启动演示模式

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">

      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

我希望只获得有关艺术家、标题和专辑的详细信息,而不是所有详细信息页面。

【问题讨论】:

    标签: c# asp.net-core visual-studio-2017


    【解决方案1】:

    亲爱的@Rocha,没有提到你想通过哪种方法获取数据,你也没有提供专辑模型属性,所以这里我只是为 MVC Core 编写 json 代码,你可以通过它获取音乐信息详细信息并显示在你的引导模式。

    IAction方法

    public IActionResult MusicDetails(int MusicID)
            {
                var varMusic = _db.Music.SingleOrDefault(aa => aa.Topicid == MusicID);
                Music obj = new Music();
                if(varMusic!=null)
                {
                    obj.Artist = varMusic.Artist;
                    obj.Title = varMusic.Title;
                    var varAlbum = _db.Album.Where(aa => aa.Topicid == MusicID);
                    List<Album> albumcollection = new List<Music>();
                    foreach(var item in varAlbum)
                    {
                        Album albumitem = new Album();
                        albumitem.item1 = item.item1;
                        albumitem.item2 = item.item2;
                        albumcollection.Add(albumitem);
                    }
                    obj.Album = albumcollection;
                }
                return Json(obj);
            }
    

    按钮 Html 代码

    <button id="btn1" type="button" asp-controller="Musics" asp-action="Details" value="1" data-toggle="modal" data-target="#exampleModal">Get Music Details</button>
    

    引导模式设计

        <!-- Modal -->
        <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
          <div class="modal-dialog" role="document">
            <div class="modal-content">
              <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                  <span aria-hidden="true">&times;</span>
                </button>
              </div>
              <div class="modal-body">
        <div class="row">
                            <div class="col-xs-2" style="text-align:right;font-weight:bold;">Artist:</div>
                            <div class="col-xs-10">
                                <span id="spanArtist"></span>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-xs-2" style="text-align:right;font-weight:bold;">Title:</div>
                            <div class="col-xs-10">
                                <span id="spanTitle"></span>
                            </div>
                        </div>
                        <hr style="margin-bottom:0px;" />
                        <table id="tblAlbum" class="table table-striped">
                            <thead>
                                <tr>
                                    <th style="width:5%;">S.No.</th>
                                    <th>Column1</th>
                                    <th>Column2</th>
                                </tr>
                            </thead>
                            <tbody id="tblalbumbody">
                                <tr>
                                    <td></td>
                                    <td></td>
                                    <td></td>
                                </tr>
                            </tbody>
                        </table>
    </div>
              </div>
              <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary">Save changes</button>
              </div>
            </div>
          </div>
        </div>
    

    Json 和 JQuery

       <script>
        $(document).ready(function () {
            $('#btn1').on('click', function (e) {
                $('#exampleModal').modal('show');
                var _MusicID = $(this).val();
                $("#tblAlbum tbody tr").remove();
                $.ajax({
                        type: 'POST',
                        url: '@Url.Action("MusicDetails")',
                        dataType: 'json',
                        data: {
                            MusicID: _MusicID
                        },
                    success: function (data) {
                        $('#spanArtist').html(data.artist);
                        $('#spanTitle').html(data.title);                       
    
                        $.each(data.particularsList, function (i, item) {
                                var rows = "<tr>" +
                                    "<td  style='text-align: center;padding:5px;'> " + item.srNo + "</td>" +
                                    "<td  style='text-align: left;padding:5px;'>" + item.item1 + "</td>" +
                                    "<td  style='text-align: left;padding:5px '>" + item.item2   + "</td>"
                                    "</tr>";
                                $('#tblalbumbody').append(rows);
                            });
                        },
                        error: function (ex) {
                            alert('Failed to retrieve data.' + ex);
                        }
                 });
                return false;
            });
       });
        <script>
    

    【讨论】:

    • 感谢您的回答,我已经更新了我的问题。感谢您的帮助,谢谢
    【解决方案2】:

    你可以使用 ViewModel 来展示你想要的,这里有一个简单的演示如下:

    1.ViewModel:

    public class ArtistViewModel
    {
        public string Artist { get; set; }
        public List<string> Title { get; set; }
    }
    

    2.专辑/Index.cshtml:

    @model IEnumerable<Album>
    <table class="table">
        <thead>
            <tr>
                <th>
                    @Html.DisplayNameFor(model => model.Artist)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.MusicID)
                </th>
                <th></th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model)
            {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.Artist)
                </td>
                <td>
                    @foreach (var music in item.Music)
                    {
                        @Html.DisplayFor(modelItem => music.MusicID)<br/>
                    }
                </td>
                <td>
                    <button type="button" id="btn1" data-id="@item.AlbumID" data-toggle="modal" data-target="#exampleModal" onclick="Click(@item.AlbumID)">detail</button>
                </td>
                <td>
            </tr>
            }
        </tbody>
    </table>
    <!-- Modal -->
    <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close" onclick="Close()">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body" id="details">
                    <table id="tblAlbum" class="table table-striped">
                        <thead>
                            <tr>
                                <th>Artist</th>
                                <th>Title</th>
                            </tr>
                        </thead>
                        <tbody id="tblalbumbody">
                        </tbody>
                    </table>
    
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal" onclick="Close()">Close</button>
                    <button type="button" class="btn btn-primary">Save changes</button>
                </div>
            </div>
        </div>
    </div>
    @section Scripts{
        <script>
            function Click(id) {
                $.ajax({
                    method: 'GET',
                    url: 'Details/' + id,
                    success: function (data) {
                        console.log(data);
                            var rows = "<tr>" +
                            "<td  style='text-align: left;'> " + data.artist + "</td>" +
                            "<td  style='text-align: left;'>" + data.title + "</td>"
                        "</tr>";
                        $('#tblalbumbody').append(rows);                
                        $('#exampleModal').modal('show');
                    },
                });
            }
            function Close() {
                $("#tblalbumbody tr").remove();
            }
        </script>
    }
    

    2.相册控制器:

    // GET: Albums
        public async Task<IActionResult> Index()
        {
            return View(await _context.Album.Include(a=>a.Music).ToListAsync());
        }
    
     public async Task<IActionResult> Details(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }
    
            var album = await _context.Albums
            .Include(a => a.Music).Where(a => a.AlbumID == id)
            .Select(a => new ArtistViewModel()
            {
                Artist = a.Artist,
                Title = a.Music.Select(m=>m.Title).ToList()
            }).FirstOrDefaultAsync();
    
            if (album == null)
            {
                return NotFound();
            }
    
            return new JsonResult(album);
        }
    

    更新:

    1.我更改detail按钮(使用data-id并添加onclick功能)

    2.另外我在模态中更改了两个close按钮(添加了一个onclick功能)

    3.更改返回类型。

    4.更改Title的类型

    5.添加索引操作

    【讨论】:

    • 感谢您的帮助。如何将这些值放入专辑 Index.cshtml 中每个专辑的模式中
    • 感谢您的帮助。但是,a.Music.Select(m =&gt; m.Title).ToList() 这一行给出了以下错误:无法将类型“System.Collections.Generic.List”隐式转换为“string”
    • 如果我将 a.Music.Select(m =&gt; m.Title).ToList() 更改为 a.Music.Select(m =&gt; m.Title).ToString() 错误消失,但我在 Index.cshtml 中的浏览器第 33 行收到未处理的异常 AspNetCore.Views_Albums_Index.ExecuteAsync()。第 33 行是@foreach (var music in item.Music)
    • 嗨 RochaCarter07,这是我的错。我更改了 ViewModel,但没有正确更新。您需要在 ViewModel 中将 Title 属性 string 更改为 List&lt;string&gt;
    • 嗨@Rena,再次感谢您。我已经按照您上面的建议进行了更改,但出现此浏览器错误:NullReferenceException:对象引用未设置为对象的实例。 Index.cshtml 中的 AspNetCore.Views_Albums_Index.ExecuteAsync() 第 22 行 @foreach (var music in item.Music)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-19
    • 2020-06-30
    • 1970-01-01
    • 2023-03-04
    • 2020-12-06
    • 2017-03-12
    • 1970-01-01
    相关资源
    最近更新 更多