Home > Back-end >  How to show selected value in a DropDownList Html Helper using ViewBag in C#
How to show selected value in a DropDownList Html Helper using ViewBag in C#

Time:03-18

So I have the following scenario in which I am using two ViewBag(s):

  1. To get the select list item
  2. To get the particular item in concern

So it looks like this:

var currentType = "2";
List<SelectListItem> contentData = new List<SelectListItem>();
contentData.Add(new SelectListItem
{
    Text = "Show 0 only",
    Value = "0",
});

contentData.Add(new SelectListItem
{
    Text = "Show 2 Only",
    Value = "2",
});


ViewBag.currentType = currentType;
ViewBag.contentData = contentData;

Now in my Razor View, I am able to generate the DropDownList like this:

@Html.DropDownList("ContentTypeId", (IEnumerable<SelectListItem>)ViewBag.contentData, null, new { @class = "form-control" , @style = "width: 150px;" })

How can I can bind my ViewBag.currentType on the drop down list so it shows the pre selected value by default when the component is rendered?

Is it even possible to use two ViewBag value in this component ?

I tried like this:

@Html.DropDownList("ContentTypeId", (IEnumerable<SelectListItem>)ViewBag.contentData, null, new { @class = "form-control" , @style = "width: 150px;", @selected= (string)ViewBag.currentType})

But not getting the correct output.

Any tips/suggestions/solutions?

CodePudding user response:

ViewBag is not working in your case, you will have to select an option manually, using Selected=true. HtmlDropDown is an outdated helper too.

Using html5 select with an asp helper is the best way to select item automatically

view

@{

var currentType = "2";
List<SelectListItem> contentData = new List<SelectListItem>();
contentData.Add(new SelectListItem
{
    Text = "Show 0 only",
    Value = "0",
});

contentData.Add(new SelectListItem
{
    Text = "Show 2 Only",
    Value = "2",
});

//or I guess you can take the from viewbag

string currentType = ViewBag.currentType;
List<SelectListItem> contentData = ViewBag.currentData
}

.....

<select  id="levels" asp-for="@currentType" 
asp-items="@contentData">
         <option value="0" > Select </option>
</select>

this is working for dropdown list

@{
currentType = ViewBag.currentType;
contentData = ViewBag.contentData;

var dropDownItems = new SelectList(contentData,"Value","Text", currentType);
}
.....

@Html.DropDownList("@currentType",@dropDownItems,"Select",new { @class = "form-control" }) 

CodePudding user response:

The SelectListItem Class has a Selected property. You can just do :

List<SelectListItem> contentData = new List<SelectListItem>{
new SelectListItem
{
    Text = "Show 0 only",
    Value = "0",
},
new SelectListItem
{
    Text = "Show 2 Only",
    Value = "2",
    Selected = true
});
  • Related