获取生成的元素“名称” HtmlHelper 扩展的属性
我正在为出现在我的许多视图中的标准 DropDownList 构建自己的 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
I am building my own HtmlHelper extensions for standard DropDownLists that appear on many of my views. On other elements I use "EditorFor" and razor generates the proper element "name" attribute for me since that is important for it to be bound to the model correctly. How would I get the correct name in my View so that my Helpers name the element appropriately?
Currently my view code looks like this, but I'd rather not hardcode the element name if I can avoid it.
<tr>
<td class="editor-label">
County:
</td>
<td class="editor-field">
@Html.CountyDropDown("CountyID")
</td>
</tr>
Here is my extension code (Which returns the list of Counties based on the current user's region):
<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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我是一个傻瓜,我已经知道如何做到这一点:
1)在 ViewModel 中给我的 Id 值一个 UIHint,如下所示:
2)将我的视图更改为仅使用 EditorFor,如下所示:
3)制作了“County.vbhtml”部分 -在我的 EditorTemplates 文件夹中查看:
4) 从我的助手中仅返回一个 IEnumerable(Of SelectListItem),而不是整个下拉 html:
I'm a dummy I already knew how to do this:
1) Gave my Id value a UIHint in the ViewModel like so:
2) Changed my View to just use EditorFor like this:
3) Made a "County.vbhtml" partial-view in my EditorTemplates folder:
4) Returned just an IEnumerable(Of SelectListItem) from my helper, not the entire drop down html: