1

I am very new to MVC and trying to do a project. I have Product model which is created from database. It has the properties like below(I am now writing all properties.)

Product
-------
ID(int)
CODE(string)
CATEGORY_ID(int)

Categories
-------
ID(int)
CODE(string)

I created the Create ActionResult for Product. And since the CATEGORY_ID is integer in the database, Visual Studio created a textbox for CATEGORY_ID. I want it to be dropdownlist which will list all the categories from the Categories table.But when the user click the Save button, it will write integer value of the selected category to Product table.

How can I do that dropdownlist? How can I pass all the categories to the Product's Create ActionResult?

Arif YILMAZ
  • 5,754
  • 26
  • 104
  • 189

2 Answers2

1

You want to use a ViewModel to shape your DB model to a presentation purpose.

Community
  • 1
  • 1
Mike Cole
  • 14,474
  • 28
  • 114
  • 194
0

In model class Product add following,

[NotMapped]
    public SelectList Categories { get; set; }

in view add

@Html.DropDownListFor(model => model.CategoryID, Model.Categories, "--Select--", new { @id="drpCommodity"})   

fill Categories in using following

public static SelectList GetDropDownList<T>(List<T> objects, string value, string text)
    {
        List<SelectListItem> items = new List<SelectListItem>();
        //var defaultItem = new SelectListItem();
        //defaultItem.Value = Convert.ToString(-1);
        //defaultItem.Text = "--Select--";
        //defaultItem.Selected = true;
        //items.Add(defaultItem);

        List<SelectListItem> lst = objects
                .Select(x =>
                        new SelectListItem
                        {
                            Value = x.GetType().GetProperty(value).GetValue(x).ToString(),
                            Text = x.GetType().GetProperty(text).GetValue(x).ToString()
                        }).ToList();

        items.AddRange(lst);
        return new SelectList(items, "Value", "Text");
    }
Smita
  • 61
  • 1