开发者

ASP.NET MVC Html.Dropdown - setting the default value

开发者 https://www.devze.com 2023-02-23 06:12 出处:网络
Yesterday I asked the following question Html.Dropdown - get the the value of each option to be the same as the text? which was answered when I found the following post What HTML helper do I use to cr

Yesterday I asked the following question Html.Dropdown - get the the value of each option to be the same as the text? which was answered when I found the following post What HTML helper do I use to create a simple dropdownlist that doesn't take in any variables? now that's all well and good however, how would I select a default value (like monthly), here's my code...

<%: Html.DropDownList("day", new SelectList(
    new Dictionary<string,string> { { "Weekly", 开发者_开发知识库"Weekly" }, { "Monthly", "Monthly" }, { "Quarterly", "Quarterly" }, { "Annually", "Annually" } },
    "Key", "Value"))
%>

Any help would be appreciated as I haven't found an example to explain this rather simple requirement, perhaps I should purchase a book on MVC?


Use this overload

    public SelectList(IEnumerable items, string dataValueField, string dataTextField, object selectedValue);

The last parameter is selected value. You could rewrite your method as

 <%: Html.DropDownList("day", new
 SelectList(
     new Dictionary<string,string> { { "Weekly", "Weekly" }, { "Monthly",
 "Monthly" }, { "Quarterly",
 "Quarterly" }, { "Annually",
 "Annually" } },
     "Key", "Value", "Monthly")) %>
0

精彩评论

暂无评论...
验证码 换一张
取 消