在我的模型中,我有一个名为Reasons
的属性。我希望用户能够从一小部分原因中进行选择。列表看起来像这样:
PR Promotional
CL Customer Related
SL Supplier Related
我尝试过使用枚举,但我似乎无法使用它。当我尝试将其与我的模型连接时,Intellisense不会将Reasons
识别为我的模型的属性(是的,它设置为public
)。最好的办法是什么?我绝对不认为在这种情况下使用数据库是必要的,我宁愿避免使用它。谢谢你的帮助。我正在使用ASP.NET MVC 5.
编辑 - 问题更新
经过一些更多的测试,我意识到问题正在发生,因为我的ViewModel的设置方式。我的ViewModel包含一个引用我的其他模型的属性,该模型引用了所有其他模型。我编写了这些类,目的是根据预定的XML结构将它们序列化为XML。这是一个例子:
<MyViewModel>
<Property>
</Property>
<ReferenceToOtherModel>
<OtherModel1>
<ReferenceToOtherModel2>
</ReferenceToOtherModel2>
</OtherModel1>
</ReferenceToOtherModel>
</MyViewModel>
总结一下,MyViewModel
是XML结构的根,所以我无法在ViewModel本身中放置一个属性作为枚举的链接。
编辑2:
我得到的错误消息是这样的:“model.otherModel1.otherModel2.Reasons is a type, which is not valid in the given context. Reasons: cannot reference a type through an expression; try 'otherModel2.Reasons' instead."
遗憾的是,如果没有完全限定名称,则无法引用othermodel2,这可以追溯到错误消息的第一句话。
答案 0 :(得分:0)
假设你有这样的枚举
public enum Reasons
{
[Display(Name = "Promotional")]
Promotional,
[Display(Name = "Customer Related")]
CustomerRelated,
[Display(Name = "Supplier Related")]
SupplierRelated
}
并且您的视图模型具有此类型的属性
public class YourViewModel
{
public Reasons Reason { set; get; }
}
您可以使用Html.EnumDropDownListFor
辅助方法
@model YourViewModel
@using (Html.BeginForm("Create", "Issue", FormMethod.Post))
{
@Html.EnumDropDownListFor(s=>s.Reason, "select one")
}
我刚使用Promotional
代替PR
,因为这对我来说更具可读性。您可以根据需要更新该部分。