I'm trying to pass view bag to a DropDownList but is not working.
Dropdownlist Error
view
<div class="form-group">
@Html.LabelFor(model => model.BanhoTosaId, "BanhoTosaId", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("TransporteId", ViewBag.BanhoTosaId, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.BanhoTosaId, "", new { @class = "text-danger" })
</div>
</div>
Controller
// GET: AgendaBTs/Create
public ActionResult Create(int id, int pet)
{
ViewBag.BanhoTosaId = new SelectList(db.BanhoTosas, "BanhoTosaId", "Tipo");
ViewBag.ClienteId = new SelectList(db.Clientes, "ClienteId", "Nome", id);
ViewBag.PetId = new SelectList(db.Pets, "PetId", "PetNome", pet);
ViewBag.TransporteId = new SelectList(db.Transportes, "TransporteId", "Tipo");
if (ViewBag.BanhoTosaId != null && ViewBag.SelectedValue != null)
{
BanhoTosa BT = db.BanhoTosas.Find(ViewBag.BanhoTosaId);
Transporte TS = db.Transportes.Find(ViewBag.TransporteId);
decimal valorSoma = BT.Valor + TS.Valor;
ViewBag.Total = valorSoma;
}
else
{
ViewBag.Total = 0;
}
return View();
}
If I let the dropdown this way @Html.DropDownList("TransporteId",null, htm.... the if in the controller you throw the else method.
How can i do to solve this?
Replace
with
You need to cast the ViewBag.BanhoTosaId:
OR
In your
Create
action replace this:By
Add then in your razor view:
you first need to make a list from data you wanna fill list by it like that :
and then use a ViewBag :
after that you will going to view and write:
this example from project i worked on it before