1

I have:

public partial class Ingredient
{
    public int IngredientID { get; set; }
    public string IngredientName { get; set; }
}

in controller:

 IEnumerable<Ingredient> ListOfIngridient =  FRE.Ingredient.Select(key => key).ToList();
 ViewBag.list = new SelectList(ListOfIngridient);

The main problem is that subscribtion of drop down label is wrong enter image description here

I want to place there 'IngredientName'. How to fix it?

0

2 Answers 2

4

When you use this constructor:

SelectList(ListOfIngridient)

The SelectList doesn't know what is a "text" or "value" field in the supplied collection. So it simply defaults to .ToString() for both. And the default value for .ToString() for an object (unless overridden in your class, which it isn't) is the name of the class.

So both the text and the value for that select in the resulting view are the string representation of each object in the collection.

You can use a different constructor to supply it with the "text" and "value" fields to use:

SelectList(ListOfIngridient, "IngredientID", "IngredientName")
Sign up to request clarification or add additional context in comments.

Comments

3

You need to use a different overload when creating your select list. There is one you can use to tell it which properties to use for the names and values.

var ingredients = FRE.Ingredient.ToList();
ViewBag.list = new SelectList(ingredients, nameof(Ingredient.IngredientID),
                                         , nameof(Ingredient.IngredientName));

You should use the nameof operator to avoid magic strings. This has several advantages over manually putting in the strings "IngredientID" and "IngredientName". If you ever use your IDE's refactoring tools to change the names of those properties, they'll automatically be updated. Also, you get Intellisense when typing them, removing the chance of making a typo.

Additionally, grabbing the ingredients can be simplified by removing the Hungarian notation. Hungarian notation goes against Microsoft's C# style guides. Also, you can use the implicit operator var instead of manually declaring what type your ingredients are. Also, there's no need for the select statement. Select statements are used to transform the item in your LINQ query, but you weren't transforming anything.

Lastly, you're passing this information via ViewBag. You should avoid ViewBag if at all possible. It's much better to pass things in a strongly typed model.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.