2

モデルの列挙型をドロップダウンリストにバインドする方法を探しています。この投稿を見つけて、2番目の回答のコードを使用しましたが、ドロップダウンリストの作成に最適です。ただし、フォームを送信すると、常に列挙の最初の値でモデルが返されます。

列挙(これは私のモデルに含まれています):

public LayoutType Layout;
public enum LayoutType
{
    Undefined = 0,
    OneColumn = 1,
    TwoColumn = 2,
    ThreeColumn = 3
}

HTML ヘルパー メソッド:

private static Type GetNonNullableModelType(ModelMetadata modelMetadata)
    {
        Type realModelType = modelMetadata.ModelType;

        Type underlyingType = Nullable.GetUnderlyingType(realModelType);
        if (underlyingType != null)
        {
            realModelType = underlyingType;
        }
        return realModelType;
    }

    private static readonly SelectListItem[] SingleEmptyItem = new[] { new SelectListItem { Text = "", Value = "" } };

    public static string GetEnumDescription<TEnum>(TEnum value)
    {
        FieldInfo fi = value.GetType().GetField(value.ToString());

        DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);

        if ((attributes != null) && (attributes.Length > 0))
            return attributes[0].Description;
        else
            return value.ToString();
    }

    public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression)
    {
        return EnumDropDownListFor(htmlHelper, expression, null);
    }

    public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression, object htmlAttributes)
    {
        ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
        Type enumType = GetNonNullableModelType(metadata);
        IEnumerable<TEnum> values = Enum.GetValues(enumType).Cast<TEnum>();

        IEnumerable<SelectListItem> items = from value in values
                                            select new SelectListItem
                                            {
                                                Text = GetEnumDescription(value),
                                                Value = value.ToString(),
                                                Selected = value.Equals(metadata.Model)
                                            };

        // If the enum is nullable, add an 'empty' item to the collection
        if (metadata.IsNullableValueType)
            items = SingleEmptyItem.Concat(items);

        return htmlHelper.DropDownListFor(expression, items, htmlAttributes);
    }

意見:

@Html.EnumDropDownListFor(model => model.Layout)

ビューをレンダリングすると、ドロップダウンリストは期待どおりに完全に入力され、正しい値が選択されます。しかし、POST を送信して値をコントローラーに戻すと、Model.Layout の値は常に「未定義」になります。どんな助けでも大歓迎です!ありがとう、

4

2 に答える 2

1

VB.Net - MVC4- Razor を使用している場合 この回答は Frigik とほぼ同じです( Thanks Frigik)

モデルで 2 つのフィールドを作成します

モデル クラス - Tag.vb

Imports System.Web.Mvc

Private _tagType As String
Private _tagTypeList As List(Of SelectListItem)

Public Property TagType() As String
        Get
            Return _tagType
        End Get
        Set(ByVal value As String)
            _tagType = value
        End Set
End Property

Public Property TagTypeList() As List(Of SelectListItem)
        Get
            Return _tagTypeList
        End Get
        Set(value As List(Of SelectListItem))
            _tagTypeList = value
        End Set
    End Property

'In the constructor

Sub New()
        TagTypeList = CommonUtility.LoadDropDownByName("TAGTYPE")
End Sub

CommonUtility クラス - CommonUtility.vb

Imports System.Web.Mvc
Imports System.Collections.Generic


Public Shared Function LoadDropDownByName(ByVal DropDownName As String) As List(Of SelectListItem)
        Dim dt As DataTable
        Dim ds As DataSet
        Dim results As List(Of SelectListItem) = Nothing
        Try
            ds = obj.LoadDropDown(DropDownName)   'Pass the dropdown name here and get the values from DB table which is - select ddlId, ddlDesc from <table name>
            If Not ds Is Nothing Then
                dt = ds.Tables(0)
                If (dt.Rows.Count > 0) Then
                    results = (From p In dt Select New SelectListItem With {.Text = p.Item("ddlDesc").ToString(), .Value = p.Item("ddlId").ToString()}).ToList()
                End If
            End If
        Catch ex As Exception
        End Try
        Return results
    End Function

ビューで

@Html.DropDownListFor(Function(x) x.TagType, Model.TagTypeList, "", New With {.id = "ddlTagType",.class = "dropDown", .style = "width: 140px"})

ここで、3 番目のパラメーター (オプション) を空にすると、最初の項目がドロップダウンに空として挿入されます。最初のパラメーターは、値が DB テーブルに既に存在する場合に入力するのに役立つ selectedItem です。

これがVB.Netを使用している人に役立つことを願っています

于 2013-06-11T18:48:41.043 に答える
0

モデルで、選択した項目 (SelectedItem) を保持する 2 つのフィールドを作成し、2 つ目のドロップダウン値 (GroupNames) を作成します。

  public string SelectedItem { get; set; }

  [Required]
  public IEnumerable<SelectListItem> GroupNames { get; set; }

次に、コンストラクターで、たとえば GroupNames を入力します

GroupNames = layer.GetAll().Select(p => new SelectListItem
                                                        {
                                                            Value = p.Id.ToString(CultureInfo.InvariantCulture),
                                                            Text = p.Name,
                                                            Selected = p.Id == someEntity.someFK
                                                        });
            SelectedItem = GroupNames.Where(p => p.Selected).Select(p => p.Value).Single();

次に、ビューでそのようにドロップダウンをレンダリングします:

 @Html.DropDownListFor(x => x.SelectedItem, Model.GroupNames)

選択された値はすべて、SelectedItem フィールドのモデルに含まれている必要があります。

于 2012-08-31T06:18:13.397 に答える