Mandar Jogalekar
Mandar Jogalekar

Reputation: 3281

Set dropdown list selected value

I am using Razor engine but not using MVC framework for my project. DropDownList is bound using following code.

var data= new List<SelectListItem>();
data.Add(new SelectListItem() {Text="abc", Value="1"});
data.Add(new SelectListItem() { Text = "def", Value = "2"});
var testDropdown= @Html.DropDownList("mydropdown",data);

I have checked answers which suggest use of new SelectList() or DropdownListFor() which I don't see in intellisense probably because it's not a MVC project but only rendering logic using cshtml pages.

I cannot convert to ViewModel or solution that involves using models.

Any easier way that I am missing to set selected value for DropDownList?

Upvotes: 0

Views: 93

Answers (2)

Whiplash450
Whiplash450

Reputation: 964

try adding 'selected = true' when you create the desired item,

data.Add(new SelectListItem() {Text="abc", Value="1", Selected=true});

SelectListItem has a property Selected which takes a boolean type. So try 'true' or 1.

For reference: https://msdn.microsoft.com/en-us/library/system.web.mvc.selectlistitem.selected(v=vs.118).aspx

Upvotes: 0

ilyabreev
ilyabreev

Reputation: 634

SelectedListItem has property Selected with setter. So you can just assign it like that

data.Add(new SelectListItem() {Text="abc", Value="1", Selected=true});

Upvotes: 1

Related Questions