@ Html.DropDownListFor how to set the default value

1

I need to set the default value displayed by a @Html.DropDownListFor

Searching found: @ Html.DropDownListFor how to set default value

So, I did it in my code:

 @Html.DropDownListFor(model => model.equipe, new SelectList(ViewBag.equiColaborador,"id","nome","Selecionar.."), htmlAttributes: new { @class = "form-control"})

But without success, the first record is always displayed.

My Controller :

// GET: Colaboradores
    public ActionResult Index()
    {
        if (Session["cod_cli"] != null)
        {
            string cod_cli = Session["cod_cli"].ToString();

            ViewBag.equiColaborador = db.Equipes.ToList();

            return View();
        }
        else
        {
            return RedirectToAction("Login", "Account");
        }
    }
    
asked by anonymous 01.08.2017 / 13:59

1 answer

3

You can do with DropDownList, which is also a cool alternative:

In Controller, if you want to set the default value, it is like this:

ViewBag.equiColaborador = new SelectList(db.Equipes.ToList(), "seuValue", "seuText", "valorPadrao");

No default value looks like this:

ViewBag.equiColaborador = new SelectList(db.Equipes.ToList(), "seuValue", "seuText");

And in the View like this:

@Html.DropDownList("equipe", (SelectList)ViewBag.equiColaborador, "-- Selecione --", new { @class = "form-control"})

In the View, where it is - Select -, if you have not put a default value in the Controller, you can place the value that will be selected there.

    
01.08.2017 / 14:22