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.