C# @Html.DropDownList或@Html.DropdownlistFor不显示当前值

C# @Html.DropDownList或@Html.DropdownlistFor不显示当前值,c#,html,asp.net,.net,C#,Html,Asp.net,.net,所以我有一个Html.DropDownList,我想在编辑页面上使用它,允许用户编辑不同配方成分的类别。因此,例如,如果用户想要编辑辣椒配方,他们会看到配方的所有不同属性,包括他们应该能够添加或删除的所有成分的列表,或者编辑配方的数量、名称和类别。我只希望有一个下拉列表来编辑类别,因为我只希望他们能够从预选的类别列表中进行选择。这是我的 <table> <tr> <th></th> </tr>

所以我有一个Html.DropDownList,我想在编辑页面上使用它,允许用户编辑不同配方成分的类别。因此,例如,如果用户想要编辑辣椒配方,他们会看到配方的所有不同属性,包括他们应该能够添加或删除的所有成分的列表,或者编辑配方的数量、名称和类别。我只希望有一个下拉列表来编辑类别,因为我只希望他们能够从预选的类别列表中进行选择。这是我的

 <table>
    <tr>
        <th></th>
    </tr>
    @for (int i = 0; i < @Model.Recipe.RecipeIngredients.Count; i++)
    {
        <tr>
            <td>@Html.EditorFor(model => model.Recipe.RecipeIngredients[i].Quantity)</td>
            <td>@Html.EditorFor(model => model.Recipe.RecipeIngredients[i].IngredientName)</td>
            <td>@Html.DropDownList("AvailableCategories")</td>
        </tr>
    }
</table>

    //// GET: /Recipe/Edit/5
    public ActionResult Edit(int? id)
    {           
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        EditViewModel vm = new EditViewModel();
        vm.Recipe = Db.Recipes.Find(id);
        if (vm.Recipe == null)
        {
            return HttpNotFound();
        }

        List<SelectListItem> items = new List<SelectListItem>();
        foreach (var item in Db.Categories)
        {
            items.Add(new SelectListItem { Text = item.CategoryName, Value = item.CategoryId.ToString() });
        }
        vm.AvailableCategories = items;
        return View(vm);
    }

public class EditViewModel
{
    public Recipe Recipe { get; set; }
    public List<SelectListItem> AvailableCategories { get; set; }

    public EditViewModel()
    {
        AvailableCategories = new List<SelectListItem>();
    }
}


public class RecipeIngredient
{
    public int IngredientId { get; set; }
    public int RecipeId { get; set; }
    public int CategoryId { get; set; }
    public string IngredientName { get; set; }
    public string Quantity { get; set; }
    public int IsOnMenu { get; set; }
    public bool IsOnTheDamnMenu
    {
        get
        {
            return IsOnMenu == 1;
        }
        set
        {
            IsOnMenu = value ? 1 : 0;
        }
    }

    public virtual Recipe Recipe { get; set; }
    public virtual Category Category { get; set; }
}

事实上,我刚刚发现我可以将更多属性传递到这个函数中。大概是

@Html.DropDownListFor(model => model.Recipe.RecipeIngredients[i].CategoryId, new SelectList(Model.AvailableCategories, "Value", "Text", Model.Recipe.RecipeIngredients[i].CategoryId),  "-Select-")

现在显示正确的类别。

显示所选类别的配方的属性是什么?配方有一个成分列表。每个成分都有一个类别,其中有一个id和一个CategoryName。您可以编辑您的问题并添加RecipeIngCredit类的定义吗?对不起,现在添加了是。