I am trying to create a DropDownList using Html.DropDownListFor
. The DropDownList is created but the value I want to select, does not get selected.
Here is my code:
@Html.DropDownListFor(model => model.Nature, new SelectList(TopicNatureHelper.All(), "Key", "Value", 2)
And here is TopicNatureHelper.All()
:
public static class TopicNatureHelper
{
public static Dictionary<int, string> All()
{
var result = new Dictionary<int, string>();
foreach (TopicNature topicNature in (TopicNature[]) Enum.GetValues(typeof(TopicNature)))
{
result.Add((int)topicNature, TopicNatureHelper.GetLocalizedDescription(topicNature));
}
return result;
}
}
public enum TopicNature
{
[Description("Owe")]
Owe = 1,
[Description("Due")]
Due = 2,
[Description("Both")]
Both = 4
}
As I said, the only problem is that the Selected value is not set. Any clues what is going wrong?
Edit
I debugged the code, and I get these surprising results:
When I am in debug mode, in the watch window, the expression
new SelectList(TopicNatureHelper.All(), "Key", "Value", 2)
creates a System.Web.Mvc.SelectList
and the item (with value 2) has Selected=true
, so I think it is Html.DropDownListFor
that doesn't render the correct output.
To see the result of Html.DropDownListFor
, I did this:
@{ var dropDown = Html.DropDownListFor(model => model.Nature, new SelectList(TopicNatureHelper.All(), "Key", "Value", 2));}
@dropDown
Inspecting dropDown
gives me this:
// base => Non-public Members => _htmlString
<select class="form-control" data-val="true" data-val-required="this is required" id="Nature" name="Nature">
<option value="1">Owe</option>
<option value="2">Due</option>
<option value="4">Both</option>
</select>
So, I think the problem is with Html.DropDownListFor
. I am totally confused.