3

I'm working with EF and MVC, new stuff to me. I have the following class:

 public class Client
{
    [Key]
    public int ClientId { get; set; }
    public Category Category { get; set; }

}

and I want to show in the View related to the "Create" ActionResult, a selectable DropDownList with all the categories to choose one.

I have a ViewModel also:

public class CategoryViewModel
{
    public int SelectedCategoryId { get; set; }
    public IEnumerable<SelectListItem> Categories { get; set; }
}

which I use in the controller:

private IEnumerable<SelectListItem> GetCategories()
    {
        var db = new MyDBContext();
        var categories = db.Categories
                    .Select(x =>
                            new Category
                            {
                                CategoryId = x.CategoryId,
                                Name = x.Name
                            });

        return new SelectList(categories, "Value", "Text");
    }

...and in the Create():

public ActionResult Create()
    {
        var model = new CategoryViewModel();
        model.Categories = GetCategories();
        return View(model);
    }

I dont know how to populate the dropdown in the view:

<div class="form-group">
        @Html.LabelFor(model => model.Category, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(WHAT GOES HERE????)

        </div>
    </div>

Thanks for rescuing me! (RE5 quote)

1
  • @Html.DropDownListFor(m => m.SelectedCategoryId, Model.Categories) but your GetCategories() method is wrong and will throw an exception. Use return db.Categories.Select(x => new SelectListItem { Value = x.CategoryId.ToString(), Text = x.Name }); Commented Jun 26, 2016 at 2:51

1 Answer 1

3

There are different overloads but this is an option:

@Html.DropDownListFor(x => x.SelectedCategoryId, Model.Categories)
Sign up to request clarification or add additional context in comments.

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.