Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SqlFunctions.StringConvert unnecessary padding added

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

like image 203
xqwzid Avatar asked May 27 '11 23:05

xqwzid


2 Answers

Change it to:

Value = SqlFunctions.StringConvert((double)status.Id).Trim(), 
like image 55
tim Avatar answered Nov 14 '22 04:11

tim


Update

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.

Original 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();
like image 37
StriplingWarrior Avatar answered Nov 14 '22 04:11

StriplingWarrior