I am Using EntityFramework as Dataaccess to View a DropDownList of Countries to my Enduser in an asp.net mvc Webapplication.
It is not a Hard thing to achieve this but i have a little struggle to find a good looking way.
But first of all some Code:
<td>
@Html.DropDownListFor(x => x.ParentId, repos.GetParents(@Model.ParentId)
</td>
Somewhere deep in the real Code:
class dummy
{
public string Text { get; set; }
public int Value { get; set; }
}
private SelectList _parents;
public SelectList Parents
{
get
{
if (_parents == null)
{
var parents = Entities.Instance.Partners.Select(x => new dummy() { Text = x.Name, Value = x.Id }).OrderBy(x => x.Text).ToList();
parents.Insert(0, new dummy());
_parents = new SelectList(parents, "Value", "Text");
}
return _parents;
}
}
public SelectList GetParents(int? parentId)
{
if (parentId != 0 && parentId.HasValue)
{
//setSelected
}
return Parents;
}
As you can see i created a ** dummy class only to copy the Data!
Why?
Because x.Id.ToString
or equivalent Methods dont work in linq to entity...
Still there is something like SqlFunctions.Tostring((double)x.ID)
this isnt the perfect solution but good enaught.
At least Until i have seen it made the Id 4 to a string
like this: "*lotsofspaces*4" and Trimming each value was too much to be considered as a good solution to me.
The most beautiful code solution is this:
new SelectList(Entities.Instance.Partners, "Id", "Name");
Beautiful isnt it? :) NO ITS NOT! Because it selects the whole Data from Partners - not only the ID and Name Column.
So my question: Can you tell me a clean and good looking way to get My Data from EntityFrame in a Dropdown while my valueField is an int
valuetype?