@Html.Dropdownlistfor how to set the default value

Asked

Viewed 1,478 times

1

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

Researching 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, unsuccessfully, the first record is always presented.

Man 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");
        }
    }

1 answer

3


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

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

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

No default value is like this:

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

And in View like this:

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

In the View, where you are -- Select --, if you have not put default value in the Controller, you can put the selected value there.

  • Friend, but between the DropDownList and the DropDownListFor, I see people talking about DropDownListFor is more recommended.. for being strongly typed and etc.. what you think?

  • I prefer not to use Dropdownlist because it has a weak type, however, in certain cases it serves me more compared to the more typed code... It will depend on your need, but the end result for the user will be the same. Here is a good explanation of the comparison between the two, https://stackoverflow.com/questions/8182280/difference-between-dropdownlist-dropdownlistfor-html-helper

  • Friend, perfect. , it worked.. but this way, I’m forcing the user to select an item.. would have to not have this obligation?

  • Where it is -- Select -- you can switch to -- None -- and in the controller, it will receive 0 or null, depending on your field, then just do the treatment there, if you need.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.