MVC3 Razor DropDownListFor枚举

试图将我的项目更新为MVC3,但我却找不到:


我有一个简单的ENUMS数据类型:


public enum States()

{

  AL,AK,AZ,...WY

}

我想在包含此数据类型的模型视图中用作DropDown / SelectList:


public class FormModel()

{

    public States State {get; set;}

}

非常简单:当我将自动生成视图用于此局部类时,它将忽略此类型。


我需要一个简单的选择列表,当我通过AJAX-JSON POST方法命中提交和处理时,将枚举的值设置为选定项。


并且比视图(???!):


    <div class="editor-field">

        @Html.DropDownListFor(model => model.State, model => model.States)

    </div>

预先感谢您的建议!


白板的微信
浏览 471回答 3
3回答

慕妹3146593

如果您想要真正简单的东西,那么还有另一种方法,这取决于您将状态存储在数据库中的方式。如果您拥有这样的实体:public class Address{&nbsp; &nbsp; &nbsp;//other address fields&nbsp; &nbsp; &nbsp;//this is what the state gets stored as in the db&nbsp; &nbsp; &nbsp;public byte StateCode { get; set; }&nbsp; &nbsp; &nbsp;//this maps our db field to an enum&nbsp; &nbsp; &nbsp;public States State&nbsp; &nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;get&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return (States)StateCode;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;set&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;StateCode = (byte)value;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp;}}然后生成下拉列表将像这样简单:@Html.DropDownListFor(x => x.StateCode,&nbsp; &nbsp; from State state in Enum.GetValues(typeof(States))&nbsp; &nbsp; select new SelectListItem() { Text = state.ToString(), Value = ((int)state).ToString() });LINQ不漂亮吗?
打开App,查看更多内容
随时随地看视频慕课网APP