【问题标题】:Get generated element "name" attribute for HtmlHelper extension为 HtmlHelper 扩展获取生成的元素“名称”属性
【发布时间】:2011-05-23 18:20:41
【问题描述】:

我正在为出现在我的许多视图中的标准 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

【问题讨论】:

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


    【解决方案1】:

    我是个傻瓜,我已经知道该怎么做了:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-30
      • 1970-01-01
      • 2023-02-25
      • 1970-01-01
      • 2013-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多