2011-05-23 59 views
0

我建立的出現在我的很多看法標準DropDownLists我自己的HtmlHelper擴展。在其他元素我用「EditorFor」和剃刀生成適當的元素「name」屬性,我自認爲是很重要的它被正確地綁定到模型。我怎麼會在我看來得到正確的名稱,以便我的助手適當命名的元素?Get生成的元素「名稱」屬性的HtmlHelper擴展

目前我的視圖代碼看起來像這樣,但我寧願不硬編碼的元素名稱,如果我能避免它。

<tr> 
    <td class="editor-label"> 
     County: 
    </td> 
    <td class="editor-field"> 
     @Html.CountyDropDown("CountyID") 
    </td> 
</tr> 

這裏是我的擴展代碼(返回縣根據當前用戶的區域列表):

<Extension()> _ 
Public Function CountyDropDown(ByVal html As HtmlHelper, ByVal name As String) As MvcHtmlString 
    Dim db As New charityContainer 
    Dim usvm As New UserSettingsViewModel 


    Dim ddl As IEnumerable(Of SelectListItem) 
    ddl = (From c In db.Counties Where c.RegionId = usvm.CurrentUserRegionID 
          Select New SelectListItem() With {.Text = c.Name, .Value = c.Id}) 

    Return html.DropDownList(name, ddl) 
End Function 

回答

0

我我已經知道如何做到這一點的虛擬:

1)給了我的ID值UIHint在視圖模型像這樣:

<UIHint("County")> 
Public Property CountyId As Nullable(Of Integer) 

2)改變我的看法,只是用EditorFor李柯這樣的:從我的輔助,而不是

@ModelType Nullable(Of Integer) 
@Html.DropDownList("", Html.CountySelectList(Model)) 

4)返回的只是一個IEnumerable(OF SelectListItem):

<td class="editor-field">     
     @Html.EditorFor(Function(x) x.CountyId) 
    </td> 

3)提出了 「County.vbhtml」 局部視在我EditorTemplates夾整個下拉html:

Public Function CountySelectList(Optional ByVal selectedId As Nullable(Of Integer) = 0) As IEnumerable(Of SelectListItem) 
     Dim db As New charityContainer 
     Dim usvm As New UserSettingsViewModel 
     Dim CurrentUserRegionID = usvm.CurrentUserRegionID 

     Dim ddl As IEnumerable(Of SelectListItem) 
     ddl = (From c In db.Counties Where c.RegionId = CurrentUserRegionID 
           Select New SelectListItem() With {.Text = c.Name, .Value = c.Id, .Selected = If(c.Id = selectedId, True, False)}) 

     Return ddl 
    End Function