It will be better if you create ViewModel for your View:
public class SampleViewModel
{
public string DropDownListValue { get; set; }
}
then in your controller's get method:
public ActionResult SomeAction()
{
var org = GetOrg(); //your org
var orgNames = GetOrgNames(); //your orgNames
// . . .
ViewBag.DropDownListValue = new SelectList(org.Select(s =>
new SampleViewModel
{
DropDownListValue = $"{s} - {orgNames[s]}"
}, "DropDownListValue", "DropDownListValue");
return View(new SampleViewModel())
}
your SomeAction
View:
@model YourAppNamespace.SampleViewModel
<h1>Hello Stranger</h1>
@using (Html.BeginForm())
{
@Html.DropDownList("DropDownListValue")
<input type="submit" value="Submit"/>
}
Note that:
The DropDownList
helper used to create an HTML select list
requires a IEnumerable<SelectListItem>
, either explicitly or
implicitly. That is, you can pass the IEnumerable<SelectListItem>
explicitly to the DropDownList
helper or you can add the
IEnumerable<SelectListItem>
to the ViewBag
using the same name for
the SelectListItem
as the model property.
We have used here implicit passing, that is we have used same name for SelectListItem
and ViewBag
(which is DropDownListValue
).
Then when you hit Submit
, you need HttpPost
method for SomeAction
:
[HttpPost]
public ActionResult SomeAction(SampleViewModel model)
{
var org = GetOrg(); //your org
var orgNames = GetOrgNames(); //your orgNames
//. . . Validation etc..
ViewBag.DropDownListValue = new SelectList(org.Select(s =>
new SampleViewModel
{
DropDownListValue = $"{s} - {orgNames[s]}"
}, "DropDownListValue", "DropDownListValue", model.DropDownListValue);
var doSomething = model.DropDownListValue; //Your selected value from DropDownList
return View(model)
}
References: DotNetFiddle Example,
Using the DropDownList Helper with ASP.NET MVC