【问题标题】:@Html.DropDownList or @Html.DropdownlistFor doesn't show current value@Html.DropDownList 或 @Html.DropdownlistFor 不显示当前值
【发布时间】:2014-11-10 00:43:29
【问题描述】:

所以我有一个 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; }
}

【问题讨论】:

  • Recipe 显示所选类别的属性是什么?
  • Recipe 有一个成分列表。每个成分都有一个类别,该类别有一个 id 和一个类别名称
  • 你能编辑你的问题并添加RecipeIngredient类的定义吗?
  • 抱歉,现在添加了。

标签: c# html asp.net .net


【解决方案1】:

我实际上只是发现我可以将更多属性传递给它。所以像

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

现在显示正确的类别。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-21
    • 1970-01-01
    • 2019-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多