What isn't working? Does your code run? Does it generate a string?
You've got at least one typo that will cause the generated string to not work in an HTML form. Should be <option value={0}>{1}</option>
Edit 2: To get the IDictionary(Of Object, String)
from your EF objects, I would write partial class implementations that add a GetSelectOptions
method to each of your objects. Or create an interface with that method in it that each of your EF objects implement. Then you'd just call the RenderSelect
method and pass in EFObject.GetSelectOptions
as the SelectOptions
parameter.
Edit: Here's how I would do this. Make your calling code responsible for reading the key/value pairs from your EF object. Then your RenderSelect extension method can be much cleaner. You don't want your view helper methods to be dependent on the structure of your model objects. And you certainly don't want your helper method to be dependent on the fact that you're using EF objects.
Public Function RenderSelect(ByVal helper As HtmlHelper, _
ByVal name As String, _
ByVal SelectOptions As IDictionary(Of Object, String), _
ByVal SelectedKey As Object, _
ByVal htmlAttributes As IDictionary(Of String, Object)) As String
Dim result = <select name=<%= name %>/>
Dim optElement As XElement
For Each opt In SelectOptions
optElement = <option value=<%= opt.Key.ToString %>><%= opt.Value %></option>
If opt.Key.Equals(SelectedKey) Then
optElement.@selected = "1"
End If
result.Add(optElement)
Next
If htmlAttributes IsNot Nothing Then
For Each attr In htmlAttributes
result.SetAttributeValue(attr.Key, attr.Value)
Next
End If
Return result.ToString
End Function
For a complete set of overloaded DropDownList functions in VB.NET, check out this file from the vbmvc.codeplex.com project from which the above code was copied and modified.
http://vbmvc.codeplex.com/sourcecontrol/changeset/view/19233?projectName=VBMVC#331689
That code has a return type of XElement, but just use result.ToString to get the string representation of the element if that's what you want.