It’s basically two steps.
Upload Instructor data to ViewBag
This step is simple. It can be done like this:
ViewBag.Instrutores = contexto.Instrutores.ToList()
In the View, you will need to assemble a SelectList
within the DropDownList
. The use may seem a little scary as below, but I will explain argument to make it clearer:
@Html.DropDownListFor(model => model.InstrutorId, ((IEnumerable<Instrutor>)ViewBag.Instrutores).Select(option => new SelectListItem
{
Text = option.NomeInstrutor,
Value = option.InstrutorId.ToString(),
Selected = (Model != null) && (Model.InstrutorId == option.InstrutorId)
}), "Selecione um Instrutor...", new { @class = "form-control" })
The first argument is the field of Id
:
model => model.InstrutorId
Reads as follows::
Having the model inside the variable model
, use InstrutorId
.
The second argument is the biggest. It is not very complex, although it seems.
((IEnumerable<Instrutor>)ViewBag.Instrutores).Select(option => new SelectListItem
{
Text = option.NomeInstrutor,
Value = option.InstrutorId.ToString(),
Selected = (Model != null) && (Model.InstrutorId == option.InstrutorId)
})
This part here:
((IEnumerable<Instrutor>)ViewBag.Instrutores)
Converts ViewBag.Instrutores
(the one we selected in Controller) to a list of instructors. IEnumerable
is one of the interfaces of List
.
Then we take this list and "select", for each element of it, an element of the type SelectListItem
:
Select(option => new SelectListItem
{
Text = option.NomeInstrutor,
Value = option.InstrutorId.ToString(),
Selected = (Model != null) && (Model.InstrutorId == option.InstrutorId)
})
That is, we are actually creating, for each instructor, a SelectListItem
, filled with instructor attributes. Note that I put each instructor in a variable option
, and need to fill in Text
(the field that will appear), Value
(the value field, ie the instructor id), and Selected
(which indicates which field will appear selected, and which I do this way for the edit screen).
Finally, the third argument indicates which text of the empty option:
"Selecione um Instrutor..."
And the last argument are additional HTML attributes that you might want to use. This one is to format the field as a input
to the Bootstrap:
new { @class = "form-control" }
how do I edit the text in label
?
If you will not internationalize, decorate the Model with
[DisplayName("Instrutor")]
public int InstrutorID { get; set; }
If it is, see this response.
Solved! Thank you, it worked perfectly!
– Bruno Hérick