0

Ajax.BeginForm を使用することを決定するまで、正常に機能していた列挙型のエディター テンプレートを作成しました。プロパティstatusには次の定義があります。

<DisplayName("Status")>
<UIHint("enum")>
Public Property status As String

私はすでに次のアプローチを試しました:

@Using Ajax.BeginForm("New", "Os", Nothing)
    @Html.EditorFor(Function(m) m.status, "Enum", New With { .enumType = GetType(OsStatus)})
End Using

@Ajax.BeginForm("New", "Os", Nothing)

@Html.EditorFor(Function(m) m.status, "Enum", New With { .enumType = GetType(OsStatus)})

@Using Html.BeginForm()
    @Html.EditorFor(Function(m) m.status, "Enum", New With { .enumType = GetType(OsStatus)})
End Using

@Html.BeginForm()
@Html.EditorFor(Function(m) m.status, "Enum", New With { .enumType = GetType(OsStatus)})

上記のどれも機能しませんでした。

私のテンプレートのコードは次のとおりです

@ModelType String

@code

    Dim options As IEnumerable(Of OsStatus)
    options = [Enum].GetValues(ViewData("enumType")).Cast(Of OsStatus)()


    Dim list As List(Of SelectListItem) = 
            (from value in options 
            select new SelectListItem With { _
                .Text = value.ToString(), _
                .Value = value.ToString(), _
                .Selected = value.Equals(Model) _
            }).ToList()
    End If
End Code

@Html.DropDownList(Model, list)

メソッドを呼び出した後.BeginForm、テンプレートは引き続き呼び出されModelますが、テンプレート内のプロパティはnull.

何か案は?

4

1 に答える 1

1

あなたのエディタ テンプレートには少なくとも 4 つの問題があります。

  • End If開口部がIfないため、エディター テンプレートが例外をスローする可能性があります。
  • 選択した値を決定するために、列挙値と文字列を比較しています:value.Equals(Model)一方、文字列と文字列を比較する必要があります:value.ToString().Equals(Model)
  • ドロップダウンリストをレンダリングするとき、Model値を名前として使用していますが、親プロパティからこのドロップダウンリストに正しい名前を付けるには、空の文字列を使用する必要があります。
  • エディター テンプレートは、OsStatus列挙型にキャストしているため、列挙型に関連付けられています。このエディター テンプレートをもう少し一般的で再利用可能なものにした方がよかったでしょう。

正しい方法は次のとおりです。

@ModelType String

@code
    Dim options = [Enum].GetValues(ViewData("enumType")).Cast(Of Object)()

    Dim list As List(Of SelectListItem) =
            (From value In options
            Select New SelectListItem With { _
                .Text = value.ToString(), _
                .Value = value.ToString(), _
                .Selected = value.ToString().Equals(Model) _
            }).ToList()
End Code

@Html.DropDownList("", list)

そして、それを呼び出す正しい方法は次のとおりです。

@Using Ajax.BeginForm("New", "Os", Nothing)
    @Html.EditorFor(Function(m) m.status, "Enum", New With { .enumType = GetType(OsStatus)})
End Using

また:

@Using Html.BeginForm("New", "Os", Nothing)
    @Html.EditorFor(Function(m) m.status, "Enum", New With { .enumType = GetType(OsStatus)})
End Using

このビューをレンダリングするときは、コントローラー アクションが実際にモデルを渡し、status文字列プロパティが列挙型に含まれる何らかの文字列値に設定されていることを確認して、ドロップダウンで正しいオプションが自動的に事前選択されるようにします。

于 2012-02-24T07:15:12.157 に答える