Как использовать разные модели в одном представлении и передать значение контроллеру - PullRequest
0 голосов
/ 20 июня 2020

У меня есть одно представление, из которого мне нужно передать Id_cliente контроллеру.

Это моя модель:

 public class Cliente
    {
        [Key]
        public int Id { get; set; }
        [Display(Name = "Azienda")]
        public string Nome_azienda { get; set; }
    }

 public class SottoCliente
    {
        [Key]
        public int Id { get; set; }
        public int Id_cliente { get; set; }
    }

В моем представлении, нажав кнопку Sotto Clienti Мне нужно передать Id_cliente от модели SottoCliente контроллеру. Я не знаю, как получить доступ к Id_cliente. Это мой вид:

@model IEnumerable<GestioneAtivita.Models.Cliente>

<table class="table">
    <thead>
        <tr>
            <th>
               ...
            </th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Nome)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Cognome)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Nome_azienda)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Cellulare)
            </td>
            <td>
                //Here I have button, and here I need somthing like  new { clienteId = item.`Id_cliente`} to pass Id_cliente to controller
                @Html.ActionLink("Sotto Clienti", "CaricaSottoCliente", new { clienteId = item.Id}, new { @class = "btn btn-danger" })
            </td>
            <td> 
                @Html.ActionLink("Modifica", "ModificaCliente", new { id = item.Id }, new { @class = "btn btn-primary" }) |
                @Html.ActionLink("Elimina", "EliminaCliente", new { id = item.Id }, new { @class = "btn btn-danger" })
                </td>
            </tr>
        }
    </tbody>
</table>

И CaricaSottoCliente - это действие, в котором я пытаюсь загрузить записи из базы данных на основе Id_cliente:

public ActionResult CaricaSottoCliente(int clienteId)
    {
        if (clienteId == null)
        {
            return RedirectToAction("Index");
        }

        SottoCliente sottoCliente = _db.tboSottoClienti
            .Include(a => a.Nome)
            .Where(a => a.Id == clienteId)
            .SingleOrDefault();

        if (sottoCliente == null)
        {
            return  RedirectToAction("Index");
        }

        var view = new ViewModels
        {
            Id = sottoCliente.Id,
            Nome = sottoCliente.Nome,
            //ListaSottoClientis = sottoCliente.getCliente.ToList()
        };
        return View(view);

Все работает нормально, но я не Я не получаю Id_cliente, вместо этого я получаю идентификатор из модели клиента.

Есть идеи, как передать Id_cliente контроллеру?

Заранее спасибо!

Ответы [ 2 ]

0 голосов
/ 20 июня 2020

Вам необходимо создать ViewModel, который содержит классы SottoCliente и Cliente.

public class ClientViewModel
{
    public Cliente Cliente { get; set; }
    public SottoCliente SottoCliente { get; set; }
}

public class Cliente
{
    [Key]
    public int Id { get; set; }
    [Display(Name = "Azienda")]
    public string Nome_azienda { get; set; }
}

public class SottoCliente
{
    [Key]
    public int Id { get; set; }
    public int Id_cliente { get; set; }
}

В представлении перейдите к таким полям, как это

@model IEnumerable<GestioneAtivita.Models.ClientViewModel>

<table class="table">
    <thead>
        <tr>
            <th>
               ...
            </th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Cliente.Nome)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Cliente.Cognome)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Cliente.Nome_azienda)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Cliente.Cellulare)
            </td>
            <td>
                //Here I have button, and here I need somthing like  new { clienteId = item.`Id_cliente`} to pass Id_cliente to controller
                @Html.ActionLink("Sotto Clienti", "CaricaSottoCliente", new { clienteId = item.SottoCliente.Id}, new { @class = "btn btn-danger" })
            </td>
            <td> 
                @Html.ActionLink("Modifica", "ModificaCliente", new { id = item.Cliente.Id }, new { @class = "btn btn-primary" }) |
                @Html.ActionLink("Elimina", "EliminaCliente", new { id = item.Cliente.Id }, new { @class = "btn btn-danger" })
                </td>
            </tr>
        }
    </tbody>
</table>
0 голосов
/ 20 июня 2020

Вы можете создать другой класс, подобный этому.

public class Parent
{
    public Cliente Cliente { get; set; }
    public SottoCliente SottoCliente { get; set; }
}

public class Cliente
{
    [Key]
    public int Id { get; set; }
    [Display(Name = "Azienda")]
    public string Nome_azienda { get; set; }
}

public class SottoCliente
{
    [Key]
    public int Id { get; set; }
    public int Id_cliente { get; set; }
}

И в модели объявите как это @model IEnumerable<GestioneAtivita.Models.Parent> и используйте свойства соответственно.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...