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
Change it to:
Value = SqlFunctions.StringConvert((double)status.Id).Trim(),
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With