1

次のドロップダウン ボックスを使用して、モデルに対して編集する値の範囲を選択しようとしています。

これまでのところ、次のコードが機能するようになりました。

@Html.DropDownList("Services", "")

しかし、本質的には、これの代わりにその文字列をここに保存したいと思います:

@Html.EditorFor(Function(model) model.ServiceName)

私の見解は次のとおりです。

@Using Html.BeginForm()
    @Html.ValidationSummary(True)
    @<fieldset>
        <legend>RequestedService</legend>

        <div class="editor-label">
            @Html.LabelFor(Function(model) model.ServiceId)
        </div>
        <div class="editor-field">
            @Html.EditorFor(Function(model) model.ServiceId)
            @Html.DropDownList("Services", "")
            @Html.ValidationMessageFor(Function(model) model.ServiceId)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
End Using

現在両方とも。

私のコントローラー:

Function AddService(id As Integer) As ViewResult
        Dim serv As RequestedService = New RequestedService
        serv.JobId = id

        Dim ServiceList = New List(Of String)()

        Dim ServiceQuery = From s In db.Services
                           Select s.ServiceName

        ServiceList.AddRange(ServiceQuery)

        ViewBag.Services = New SelectList(ServiceList)

        Return View(serv)
    End Function

そして最後に私のモデル:

Imports System.Data.Entity
Imports System.ComponentModel.DataAnnotations

Public Class RequestedService

Public Property RequestedServiceId() As Integer


Public Property ServiceId() As Integer

<Required()>
<Display(Name:="Job Number *")>
Public Property JobId() As Integer

<Required()>
<Display(Name:="Station ID *")>
Public Property StationId() As Integer

End Class
4

1 に答える 1

1

問題SelectListは、選択リストに値と表示テキストを伝える必要があることです。文字列のリストのみを渡すことはできません。正しく入力するには、次のようにキーと値を追加します

Dim ServiceQuery = (From s In db.Services
                       Select s)

こんな感じかもしれません サービス関連のIDが必要な場合

ViewBag.Services = New SelectList(ServiceList, s.IDServices, s.ServiceName)

または、このように値のテキストのみが必要な場合

ViewBag.Services = New SelectList(ServiceList, s.ServiceName, s.ServiceName)

アップデート

これを達成するには、ビューとあなたのアクションを変更する必要があります。

アクションの最初に、Viewbag 要素の名前を次のように変更します。

ViewBag.ServiceId = New SelectList(ServiceList, s.IDServices, s.ServiceName)

今、あなたの見解の明らかな変化は

@Using Html.BeginForm()
@Html.ValidationSummary(True)
@<fieldset>
    <legend>RequestedService</legend>

    <div class="editor-label">
        @Html.LabelFor(Function(model) model.ServiceId)
    </div>
    <div class="editor-field">
        @Html.DropDownList("ServiceId", "")
        @Html.ValidationMessageFor(Function(model) model.ServiceId)
    </div>

    <p>
        <input type="submit" value="Create" />
    </p>
</fieldset>

使用終了

だからあなたは必要ありません

@Html.EditorFor(Function(model) model.ServiceId)

ユーザーがドロップダウンリストからオプションを選択して作成ボタンをクリックすると、ServiceID 属性が自動的にクラスにマップされます。これは、mvc3 が要素の名前と連携して、すべての魔法の作業を実行することです。

于 2012-08-13T19:00:11.340 に答える