Use more than one template in View - C# MVC

Asked

Viewed 1,601 times

1

I have two tables in my bank: Celular and Marca. To register a mobile phone, I need to select a brand for it, ie two models in a view. Like I do to make two Models are accessed in the same view?

Celularcontroller

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 cell phone 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 table of registered cell phones

 <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 saw about putting the @model at the beginning of the index, but I know that this works if it is a model, for several I have no idea how I should declare.

2 answers

2

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

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

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

    ...

    public virtual Marca Marca { get; set; } 
}

You send only Celular to the View, with a selection of type Marca in Viewbag. I am assuming you are 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 something else entirely:

[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 -->
}

0

You already have a model class that is a composition, IE, contains brands and cell phones. This is the only model you need.

If you want the user to select a specific brand and mobile phone on 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 any 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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.