2

I have a signup form. I want users can select their pet's race using a select list in html. So i decided to use Html.DropDownListFor() Html helper.

In my model:

public class PetModel
{
    public long id { get; set; }
    public short gender { get; set; }
    public short type { get; set; }
    public string name { get; set; }
    public int raceID { get; set; }
    public int birthYear { get; set; }
    public int weight { get; set; }
    public bool neutered { get; set; }

    public IEnumerable<SelectListItem> raceList { get; set; }
}

And i want to populate a drop down list for raceList that users can select their pet's race.

So i created a controller for a partial view

public PartialViewResult _SignupPet(PetModel model)
{
    model.raceList = entity.PetRaces.Select(w => new SelectListItem { Text = w.name, Value = w.id.ToString() });

    return PartialView(model);
}

And in my view:

@Html.DropDownListFor(m=>m.raceID, Model.raceList)

But i'm receiving this error.

LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression.

Now i'm wondering about this. I generally use drop down list to select an id and show user a text instead of ids. How will i use this Html.DropDownListFor() helper in my projects. Am i using a wrong approach?

Liam
  • 27,717
  • 28
  • 128
  • 190
Murat Erdogan
  • 798
  • 2
  • 10
  • 21
  • Could you pass in w.name as both text and Id? Then use the name in your controller action? I've had similar issues, LINQ cannot convert the ToString(). – Lotok May 31 '13 at 10:34

2 Answers2

1

Your Unique ID for the SelectListItem needs to be a string. You cannot do a conversion in the LINQ as it won't translate. I have got around it by using the name as both text and Id as in my case it was unique.

Another example of this same question here: Linq int to string

Community
  • 1
  • 1
Lotok
  • 4,517
  • 1
  • 34
  • 44
  • I have a FK relation Pets anf PetRaces in my DB. So i can't set it to the string. – Murat Erdogan May 31 '13 at 10:47
  • Its a limitation in LINQ to Entities. You could extract the data and then loop through to create the List in code. That way you can do the conversion. Ugly solution but no other way past it – Lotok May 31 '13 at 10:48
  • Thanks for your support. I've found a workaround thanks to you :) – Murat Erdogan May 31 '13 at 10:51
  • Remember and mark solution accepted if it answers your question. Glad to help, shame it's not elegant. I had same issue a few weeks back – Lotok May 31 '13 at 10:52
1

I couldn't solve my original problem but i found an alternative solution. In my controller i changed the code

model.raceList = entity.PetRaces.Select(w => new SelectListItem { Text = w.name, Value = w.id.ToString() });

to

model.raceList = entity.PetRaces.Select(w => new SelectListItem { Text = w.name, Value = SqlFunctions.StringConvert((double)w.id).Trim() });
Murat Erdogan
  • 798
  • 2
  • 10
  • 21