2012-08-13 67 views
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 
+0

你能告訴我們你的行爲和你的模型嗎? – Jorge 2012-08-13 15:54:38

+0

編輯如上 – NickP 2012-08-13 18:38:58

回答

1

這是有問題的SelectList你需要告訴給seleclist,這是價值,什麼是顯示文本。你不能只傳遞字符串的列表,以正確填充,添加鍵值像這樣

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

值也能像這樣在您需要相關服務

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

1D情況或者,像這樣的情況下,你需要的唯一的文本值

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

UPDATE

要做到這一點,您需要修改視圖和您的操作。

首先在你的行動改變你的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> 

末使用

所以你不」 t需要

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

當用戶從下拉列表中選擇選項並單擊創建按鈕時,屬性ServiceID將自動映射到您的類中,即mvc3與該元素的名稱一起工作,爲您做所有的魔術工作

+0

這很有道理!謝謝。我知道我現在已經創建了一個下拉框,但是我怎麼告訴我的視圖需要採用選中的id並將其放在model.ServiceId中,如@ Html.EditorFor(Function(model)model.ServiceId)做? – NickP 2012-08-13 19:05:39

+0

檢查我的答案的更新 – Jorge 2012-08-13 19:12:26