获取HtmlHelper扩展的生成元素“name”属性

时间:2011-05-23 18:20:41

标签: asp.net-mvc-3 razor html-helper

我正在为我的许多视图中出现的标准DropDownLists构建自己的HtmlHelper扩展。在其他元素上我使用“EditorFor”并且razor为我生成适当的元素“name”属性,因为这对于它正确绑定到模型很重要。如何在我的视图中获得正确的名称,以便我的助手适当地命名该元素?

目前我的视图代码看起来像这样,但如果可以避免,我宁愿不对元素名称进行硬编码。

<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

1 个答案:

答案 0 :(得分:0)

我是个假人我已经知道如何做到这一点:

1)在ViewModel中给我的Id值一个UIHint,如下所示:

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

2)将我的视图更改为仅使用EditorFor:

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

3)在我的EditorTemplates文件夹中制作了“County.vbhtml”部分视图:

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

4)从我的助手返回一个IEnumerable(Of SelectListItem),而不是整个下拉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