I would eliminate the ViewBags
of my jobs and use ViewModel
simply because the development becomes much more scalable and easy to maintain, so I would start creating a ViewModel with the properties you need
public class SelectViewModel
{
public int SelectedOption { get; set; }
public IEnumerable<SelectListItem> Lista { get; set; }
}
And we continue with the obtaining of the data and the selection of the default option that you want to show:
public ActionResult MiAccion()
{
List<SelectListItem>data = new List<SelectListItem>
{
new SelectListItem{ Text="Chile", Value = "1" },
new SelectListItem{ Text="Argentina", Value = "2" },
new SelectListItem{ Text="España", Value = "3" },
new SelectListItem{ Text="Brasil", Value = "4" },
new SelectListItem{ Text="Paraguay", Value = "5" },
new SelectListItem{ Text="Colombia", Value = "6" },
new SelectListItem{ Text="Ecuador", Value = "7" },
new SelectListItem{ Text="Perú", Value = "8" },
new SelectListItem{ Text="Venezuela", Value = "9" },
new SelectListItem{ Text="Bolivia", Value = "10" }
};
string optionSelected = string.Empty;
foreach (SelectListItem item in data)
{
if (item.Value == "6")
optionSelected = item.Value;
}
SelectViewModel model = new SelectViewModel
{
SelectedOption = int.Parse(optionSelected),
Lista = data.Select(x => new SelectListItem
{
Value = x.Value,
Text = x.Text
})
};
return View(model);
}
And finally we link the model to the view with the data:
@model SelectViewModel
<h2>@ViewBag.Title.</h2>
<h3>@ViewBag.Message</h3>
@Html.DropDownListFor( x => x.SelectedOption, Model.Lista)
I've attached the result to you in .NET Fiddle link