[RESOLVED]Dynamically binding @Html.DropDownListFor with value and text fields

Hi ,

I ma having a Model class with 2 fields ID and MGroup. I need to dynamically bind a ddl with ID as value filed and MGroup ad Text field with one selected value ("selected  text "in in edit view).

I am filling the ddl from the controller using viewbag as follows

   List<string> marketgrouplist = new List<string>();
            marketgrouplist = listmodel.sourceData.Select(x => x.MGroup).Distinct().ToList();
           // ViewBag.ListofMarketGroup = marketgrouplist.Select(x => new SelectListItem() { Text = x.ToString() });
            ViewBag.ListofMarketGroup = new SelectList( marketgrouplist, selectedmg);

In the controller "listmodel.sourceData" contains all the records including  "ID" as well as "MGroup". Here i am displaying only Text field values. But i need to attach the ID from the model  as the "Value" field of the DDL.

Here the selectedmg is the selected text for that record in edit mode and my html part is as follows

<div class="form-group">
            @Html.LabelFor(model => model.MarketGroup, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
               @Html.DropDownListFor(model => model.MarketGroup,(SelectList) ViewBag.ListofMarketGroup)
            </div>
        </div>

Please help me

Thanks in advance

VIdya

Hi Vidya,

You are doing it right. But you have a list of string, instead use List of Object you want to display and in selectlistitem give Object.Id as value and Object.MGroup as Text. Ex:

Instead

List<string> marketgrouplist = new List<string>();
            marketgrouplist = listmodel.sourceData.Select(x => x.MGroup).Distinct().ToList();
ViewBag.ListofMarketGroup = marketgrouplist.Select(x => new SelectListItem() { Text = x.ToString() });

do: 

            List<model> marketgrouplist = lookupCodeService.FetchCodes(codeType).OrderBy(lkp => lkp.Name).ToList();
            SelectList lookUpList = new SelectList(marketgrouplist, "ID", "MGroup");  //// ID & MGroup are properties in your model, will be taken as Tex & Value
            return lookUpList;
            ViewBag.ListofMarketGroup = lookUpList;

Leave a Reply