Reputation: 55
I create a new form and I want view name based on id in another table, but the id can't view in the dropdown list:
This is the view:
<div class="form-group">
<label class="control-label col-md-2">ID Operator</label>
<div class="col-md-10">
@Html.DropDownList("idOp", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.idOp, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2">Name</label>
<div class="control-label col-md-10">
@Html.EditorFor(model => model.tbl_operator.nama, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.tbl_operator.nama , "", new { @class = "text-danger" })
</div>
</div>
This is the controller :
public ActionResult Create()
{
ViewBag.idEx = new SelectList(db.tbl_exercises, "idEx");
ViewBag.idOp = new SelectList(db.tbl_operator, "idOp");
return View();
}
Maybe I'm missing the code.
Upvotes: 0
Views: 1370
Reputation: 1
SelectList
is defined as
public SelectList(IEnumerable items, string dataValueField, string dataTextField);
In your controller, try to use
ViewBag.idOp = new SelectList(db.tbl_operator, "idOp","idOp");
Upvotes: 0
Reputation: 18975
You need choose what field is Name
, Value
for SelectList
like
ViewBag.idEx = new SelectList(tbl_exercises, "Value", "Name");
I made an example base on your code
var tbl_exercises = new List<exercises>
{
new exercises
{
Name = "Name 1",
Value = 10
},
new exercises
{
Name = "Name 2",
Value = 11
}
};
ViewBag.idEx = new SelectList(tbl_exercises, "Value", "Name");
Upvotes: 0