Populate DropDownList in MVC 5

前端 未结 3 589
-上瘾入骨i
-上瘾入骨i 2021-02-15 17:33

Here is my code for my AddNewProductViewModel

using AccessorizeForLess.Data;
using System.Collections.Generic;
using System.ComponentModel.DataA         


        
3条回答
  •  执笔经年
    2021-02-15 18:12

    First I would change your ViewModel to include a SelectedCategoryId and I would change your options to be Categories.

    Without seeing the code for your get I am assumbing ProductCategory is something like the following:

    public class ProductCategory {
      public int Id {get;set;}
      public string Name { get;set;}
    }
    

    Your razor mark-up would them become:

    @Html.LabelFor(model => model.Categories, new { @class = "control-label col-md-2" })
    @Html.DropDownListFor(model => model.SelectedCategoryId, new SelectList(Model.Categories, "Id", "Name"), "- Please Select -") @Html.ValidationMessageFor(model => model.Categories)

    The first parameter is the selected catgegory and your options are populated from Categories.

    WorkingFiddle

提交回复
热议问题