Reputation: 798
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?
Upvotes: 2
Views: 122
Reputation: 798
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() });
Upvotes: 1
Reputation: 4607
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
Upvotes: 1