簡體   English   中英

如何使用枚舉中的值從ASP.NET MVC Web應用程序中的模型填充下拉列表?

[英]How can I use values from an enum to populate a dropdownlist from my model in an ASP.NET MVC web application?

在我的模型中,我有一個名為Reasons的屬性。 我希望用戶能夠從一小部分原因中進行選擇。 該列表將如下所示:

PR   Promotional

CL   Customer Related

SL   Supplier Related

我嘗試為此使用枚舉,但似乎無法正常工作。 當我嘗試將Reasons作為模型的屬性時,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,該名稱可以追溯到錯誤消息的第一句。

假設您有這樣的枚舉

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因為這對我而言更具可讀性。 您可以根據需要更新該部分。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM