Search code examples
c#asp.net-mvclinqlinq-to-sqlviewbag

Using ViewBag to Fill Dropdown with Custom Text


I'm using a ViewBag to fill Dropdown like this:

Controller:

ViewBag.bolumList = db.SbtBolum.OrderBy(s => s.BolumAd)

View:

@Html.DropDownListFor(model => model.YGKisiBolum.Bolum, new     SelectList(ViewBag.bolumList, "BolumID" , "BolumAd"), "Seçiniz", new { @class = "form-control" })

Now i want to show combined two columns in text field like in SQL:

SELECT BolumID As Value, BolumAd+" "+BolumExtra AS Text FROM SbtBolum

How can i do this using ViewBag and Linq?


Solution

  • var values = db.SbtBolum.OrderBy(s => s.BolumAd).ToList().Select(s => SelectListItem
    {
        Value = s.BolumID.ToString(),
        Text = s.BolumAd + " " + s.BolumExtra,
    });
    ViewBag.bolumList = values;
    

    and in your view:

    @Html.DropDownListFor(
        model => model.YGKisiBolum.Bolum, 
        (IEnumerable<SelectListItem>)ViewBag.bolumList, 
        "Seçiniz", 
        new { @class = "form-control" }
    )
    

    This being said/shown, I would completely recommend against this approach. I would rather use a strongly typed view model for this purpose and get rid of the ViewBag.