As jfar posted, use:
string selectedValue = "1";
SelectListItem[] selectListItems = Enum.GetNames(typeof(MyEnumeration)).Select(
s => new SelectListItem { Text = s, Value = s, Selected = s == selectedValue}).ToArray();
which is from MVCContrib, you don't to include the DLL, this is just code found in MVCContrib.
To protect against CSRF(Cross Site Request Forgery), you can use the <%= Html.AntiForgeryToken() %>
in the view under the respective form that will be posted, and decorate the appropriate action with [ValidateAntiForgeryToken]
. More details on the Html.AntiForgeryToken()
can be found here.
EDIT As per Comment
Well first, you'll need to place the SelectListItem[]
in the ViewData so you can access it in the view:
Action
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult MyView(string enumValue)
{
string selectedValue = "1"; // fill this with the value you want to be selected
SelectListItem[] selectListItems = Enum.GetNames(typeof(MyEnumeration)).Select(
s => new SelectListItem { Text = s, Value = s, Selected = s == selectedValue}).ToArray();
ViewData["enumValue"] = selectListItems;
return View();
}
and in your view the following form will work.
<form method="post">
<%= Html.AntiForgeryToken() %>
<%= Html.DropDownList("enumValue") %>
</form>
The HTML helper will output the proper select
control.
Back in your controller, this is the action that will accept the form post
[ValidateAntiForgeryToken]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult MyView(int enumValue)
{
// enumValue will have the selected value
ViewData["Message"] = "You selected the Enum name" + Enum.GetName(typeof(MyEnumeration), enumValue);
return View();
}