首页 > 解决方案 > 按 id 从数据库中加载行

问题描述

我有两种方法试图根据 Id 从数据库加载记录。
这些是我的方法:

private List<Cliente> GetCLienti(int clienteId) //to load Clients from DB 
{
    var tuttiClienti = _db.tboSottoClienti//Not sure if this query works 
              .Where(c => c.Id_cliente == clienteId)
             .FirstOrDefaultAsync();
    //var tuttiClienti = _db.tboClienti.ToList();
    return tuttiClienti;  //I need to return LIST
}

private List<SottoCliente> GetSottoCliente(clienteId)
{
    var tuttiSottoClienti = _db.tboSottoClienti.ToList();
    return tuttiSottoClienti;
}

这是在视图中显示它的方法:

public IActionResult CaricaSottoCliente(int clienteId)
{
    ViewBag.Cliente = GetCLienti();
    ViewBag.SottoCliente = GetSottoCliente();
    return View();
}

这是我的看法:

<table class="table table-hover">
    <tr>
        <th>Id</th>
        <th>Nome</th>
        <th>Cognome</th>
        <th>Azienda</th>
        <th>Cellulare</th>
    </tr>
    @foreach (GestioneAtivita.Models.SottoCliente sottoCliente in ViewBag.SottoCliente)
    {
        <tr>
            <td>@sottoCliente.Id</td>
            <td>@sottoCliente.Nome</td>
            <td>@sottoCliente.Cognome</td>
            <td>@sottoCliente.Azienda</td>
            <td>@sottoCliente.Cellulare</td>
        </tr>

    }
</table>

<p><b>Cliente List</b></p>

<table class="table table-hover">
    <tr>
        <th>Id</th>
        <th>Code</th>
        <th>Name</th>
        <th>Enrollment No</th>
    </tr>
    @foreach (GestioneAtivita.Models.Cliente cliente in ViewBag.Cliente)
    {
        <tr>
            <td>@cliente.Nome</td>
            <td>@cliente.Cognome</td>
            <td>@cliente.Nome_azienda</td>
            <td>@cliente.Cellulare</td>
        </tr>

    }
</table>  

最后,这就是我将 ID 从另一个视图传递给控制器​​的方式:

<td>
   @Html.ActionLink("Sotto Clienti", "CaricaSottoCliente", new { clienteId = item.Id }, new { @class = "btn btn-outline-success" })
</td>

如何ListGetCLienti(int clienteId)方法中返回 a ?有什么建议么?提前致谢!

标签: c#asp.netasp.net-mvcasp.net-core

解决方案


您正在使用FirstOrDefaultAsync()但您没有使用await它。您的方法都不是asyncFirstOrDefault(). 但是作为您的方法作为返回类型,List<Cliente>您应该使用.ToList()如下所示。

private List<Cliente> GetCLienti(int clienteId) //to load Clients from DB 
{
    var tuttiClienti = _db.tboSottoClienti//Not sure if this query works 
              .Where(c => c.Id_cliente == clienteId)
              .ToList();
    //var tuttiClienti = _db.tboClienti.ToList();
    return tuttiClienti;  //I need to return LIST
}

您需要将clienteId值传递给GetCLienti它有参数。

public IActionResult CaricaSottoCliente(int clienteId)
{
    ViewBag.Cliente = GetCLienti(clienteId);
    ViewBag.SottoCliente = GetSottoCliente();
    return View();
}

推荐阅读