Get generated element "name" attribute for HtmlHelper extension
I am building my own HtmlHelper extensions for standard DropDownLists that appear on many of my views. O开发者_开发技巧n 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
I'm a dummy I already knew how to do this:
1) Gave my Id value a UIHint in the ViewModel like so:
<UIHint("County")>
Public Property CountyId As Nullable(Of Integer)
2) Changed my View to just use EditorFor like this:
<td class="editor-field">
@Html.EditorFor(Function(x) x.CountyId)
</td>
3) Made a "County.vbhtml" partial-view in my EditorTemplates folder:
@ModelType Nullable(Of Integer)
@Html.DropDownList("", Html.CountySelectList(Model))
4) Returned just an IEnumerable(Of SelectListItem) from my helper, not the entire drop down 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
精彩评论