Use more than one model in View - C # MVC

1

I have two tables in my database: Celular and Marca . To register a cell phone, I need to select a tag for it, ie two models in a view . How do I get two Models to be accessed in the same view?

CellularController

public class MarcaCelularViewModel
{
    public List<Celular> celulares { get; set; }
    public List<Marca> marcas { get; set; }
}

public class CelularController : Controller
{
    [HttpGet]
    public ActionResult Index()
    {
        MarcasDAO mDAO = new MarcasDAO();
        CelularDAO cDAO = new CelularDAO();
        List<Celular> lista_celular = new List<Celular>();
        lista_celular = cDAO.getCelular();
        List<Marca> lista_marcas = new List<Marca>();
        lista_marcas = mDAO.getMarcas();
        var model = new MarcaCelularViewModel { celulares = lista_celular, marcas = lista_marcas };  
        return View(model);
    }

View in the mobile registration section

<form method="post">
            <div class="form-group">
                <label for="nomeCelular">Nome</label>
                <input type="text" name="nomeCelular" class="form-control" required />
            </div>
            <div class="form-group">
                <label for="modeloCelular">Modelo</label>
                <input type="text" name="modeloCelular" class="form-control" required />
            </div>
            <div class="form-group">
                <label for="idMarca">Marca</label>
                <select name="idMarca" class="form-control">
                    <option selected value="">---</option>
                    @foreach (var item in Model)
                    {
                        ...Preenche com as marcas cadastradas no banco
                    }
                </select>
            </div>
            <button type="submit" class="btn">Adicionar Celular</button>
        </form>

View in the part of the mobile phones table

 <table class="table table-hover" style="background-color:#ffffff; border-radius:10px;">
        <thead>
            <th>ID</th>
            <th>Nome</th>
            <th>Modelo</th>
            <th>Marca</th>
        </thead>
        <tbody>
            @if (Model != null)
            {
                foreach (var item in Model)
                {
                    <tr>
                        <td>@Html.DisplayFor(Model => item.idCelular)</td>
                        <td>@Html.DisplayFor(Model => item.nomeCelular)</td>
                        <td>@Html.DisplayFor(Model => item.modeloCelular)</td>
                        <td>@Html.DisplayFor(Model => item.idMarca)</td>
                    </tr>
                }
            }
        </tbody>
    </table>

I've seen about putting @model at the beginning of the index, but I know this works for if it's a template, for some I do not have a clue how to declare it.

    
asked by anonymous 10.04.2017 / 04:47

2 answers

1
  

To register a mobile, I need to select a brand for it, ie two models in a view .

Wrong. If Celular belongs to a Marca , that is:

public class Celular
{
    [Key]
    public int CelularId { get; set; }
    public int MarcaId { get; set; }

    ...

    public virtual Marca Marca { get; set; } 
}

You only send Celular to View , with a selection of type Marca in ViewBag . I'm assuming you're using (wrong) the Entity Framework:

public class CelularController : Controller
{
    [HttpGet]
    public ActionResult Index()
    {
        // Não precisa nada disso aqui, então comentei tudo.
        // MarcasDAO mDAO = new MarcasDAO();
        // CelularDAO cDAO = new CelularDAO();
        // List<Celular> lista_celular = new List<Celular>();
        // lista_celular = cDAO.getCelular();
        // List<Marca> lista_marcas = new List<Marca>();
        // lista_marcas = mDAO.getMarcas();
        // var model = new MarcaCelularViewModel { celulares = lista_celular, marcas = lista_marcas };
        var model = contexto.Celulares
                            .Include(c => c.Marca)
                            .ToList();

        return View(model);
    }

View :

<table class="table table-hover" style="background-color:#ffffff; border-radius:10px;">
    <thead>
        <th>ID</th>
        <th>Nome</th>
        <th>Modelo</th>
        <th>Marca</th>
    </thead>
    <tbody>
        @if (Model != null)
        {
            foreach (var item in Model)
            {
                <tr>
                    <td>@Html.DisplayFor(Model => item.idCelular)</td>
                    <td>@Html.DisplayFor(Model => item.nomeCelular)</td>
                    <td>@Html.DisplayFor(Model => item.modeloCelular)</td>
                    <td>@Html.DisplayFor(Model => item.Marca.Nome)</td>
                </tr>
            }
        }
    </tbody>
</table>

Registration is another thing completely different:

[HttpGet]
public ActionResult Create()
{
    ViewBag.Marcas = contexto.Marcas.ToList();
    return View();
}

View :

@model SeuProjeto.Models.Celular
@using SeuProjeto.Models

<!-- form method="post" -->
@using (Html.BeginForm())
{
        <div class="form-group">
            <label for="nomeCelular">Nome</label>
            <!-- input type="text" name="nomeCelular" class="form-control" required /-->
            @Html.EditorFor(m => m.nomeCelular, new { htmlAttributes: new { @class = "form-control" } })
        </div>
        <div class="form-group">
            <label for="modeloCelular">Modelo</label>
            <!-- input type="text" name="modeloCelular" class="form-control" required /-->
            @Html.EditorFor(m => m.modeloCelular, new { htmlAttributes: new { @class = "form-control" } }
        </div>
        <div class="form-group">
            <label for="idMarca">Marca</label>
            <!-- select name="idMarca" class="form-control">
                ...
            </select -->
            @Html.DropDownListFor(m => m.idMarca, ((IEnumerable<Marca>)ViewBag.Marcas).Select(option => new SelectListItem {
                Text = option.Nome,
                Value = option.idMarca.ToString()
            }), "Selecione...", new { @class = "form-control" })
        </div>
        <button type="submit" class="btn">Adicionar Celular</button>
    <!-- /form -->
}
    
18.04.2017 / 17:55
0

You already have a template class that is a composition, that is, it contains tags and mobile phones. This is the only template you need.

If you want the user to select a specific brand and phone on the screen, you need to add two more properties:

public class MarcaCelularViewModel {
    public List<Marca> marcas { get; set; }
    public List<Celular> celulares { get; set; }

    public Marca marcaSelecionada { get; set; }
    public Celular celularSelecionado { get; set; }
}

On a given page (assuming your classes have properties called "id" and "description"):

@model MarcaCelularViewModel
<!-- o código abaixo deve vir dentro de um formulário -->
@Html.DropDownForListFor(m => m.marcaSelecionada, new SelectList(m.marcas, "id", "descricao"))
@Html.DropDownForListFor(m => m.celularSelecionado, new SelectList(m.celulares, "id", "descricao"))

When the screen is mounted you will have two selects, one to choose brand and the other to choose mobile. When the user posts the page, you will know what the user's choices were through the suggested properties for your template.

    
10.04.2017 / 14:54