These are basically two steps.
Upload Instructor data in ViewBag
This step is simple. It can be done like this:
ViewBag.Instrutores = contexto.Instrutores.ToList()
In View , you need to mount a SelectList
within DropDownList
. The usage may seem a little scary as below, but I'll explain the 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
It reads as follows:
Having the model inside the variable model
, use InstrutorId
.
The second argument is the largest. 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 List
interfaces.
Then, we take this list and "select", for each element of it, an element of 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 the instructor attributes. Notice that I put each instructor in a variable option
, and I need to fill Text
(the field that will appear), Value
(the value field, that is, the Instructor Id), and Selected
indicates which field will appear selected, and what I do for the edit screen).
Finally, the third argument indicates the empty option text:
"Selecione um Instrutor..."
And the last argument are additional HTML attributes that you might want to use. This is to format the field as a input
for Bootstrap :
new { @class = "form-control" }
How do I edit text in label
?
If you are not going to internationalize, decorate Model with
[DisplayName("Instrutor")]
public int InstrutorID { get; set; }
If it is, see this answer .