Reputation: 520
In my ViewModel i am returning the following for a dropdown list:
public IEnumerable<SelectListItem> Statuses
{
get
{
using (var context = new AssetManager.Models.AssetManagerEntities())
{
var query = from status in context.AssetStatuses
where status.Reserved != true
select new SelectListItem()
{
Value = SqlFunctions.StringConvert((double)status.Id),
Text = status.Name,
Selected = false
};
return query.ToList();
}
}
}
Then in my View it goes a little like this:
@Html.DropDownListFor(model => model.Status, (IEnumerable<SelectListItem>)Model.Statuses)
This all works ok, except that SqlFunctions.StringConvert, by default makes the string a length of 10, so i end up with this in the html:
<option value=" 7">Free to loan</option>
Take note of the spacing in the value field. This is a problem, because my ViewModel requires this field to be an int.
I could simply specify the length parameter but this is not dynamic.
Has anyone seen this problem, or have a resolution to it?
Thanks, Nick
Upvotes: 17
Views: 6269
Reputation: 156524
Tim's answer below is a better solution than this one, but I am unable to delete the accepted answer, and the OP has not responded to my requests to accept his answer.
The easiest way to do this would probably be to offload the conversion effort onto your server, rather than the data context. If you were separating your data tier from your presentation tier, this would happen automatically. But for simplicity's sake, I'll just stick with your current architecture:
var query = from status in context.AssetStatuses
where !status.Reserved
select new
{
status.Id,
status.Name
};
return query.AsEnumerable()
.Select(status => new SelectListItem
{
Value = status.Id.ToString(),
Text = status.Name,
Selected = false
})
.ToList();
Upvotes: 2
Reputation: 3167
One other option that works with LINQ to Entities is to do a concatenation with an implicit type conversion such as Value = "" & status.Id
. However, this will cause issues that have to be worked around if you want to use multiple concatenation using this method.
Upvotes: 0
Reputation: 1369
Change it to:
Value = SqlFunctions.StringConvert((double)status.Id).Trim(),
Upvotes: 35
Reputation: 8552
public IEnumerable<SelectListItem> Statuses
{
get
{
using (var context = new AssetManager.Models.AssetManagerEntities())
{
return (from status in context.AssetStatuses.ToList()
where status.Reserved != true
select new SelectListItem()
{
Value = status.Id.ToString(),
Text = status.Name,
Selected = false
});
}
}
}
Upvotes: 0