You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core中RecipeIngredient创建视图下拉框无数据问题排查

问题排查与解决方案

核心问题分析

  • GET请求未初始化下拉数据:打开创建页面的[HttpGet] Create()方法没有加载食谱和食材数据到ViewBag,导致页面初始化时下拉框无选项。
  • POST请求逻辑错误:原POST方法中,ViewBag的赋值被放在ModelState.IsValid分支内,且无论验证成功与否都直接重定向到Index页面。即使验证失败,ViewBag数据也无法传递回视图(重定向会丢失ViewBag/ViewData数据)。

修正后的控制器实现

public class RecipeIngredientController : Controller
{
    private readonly ApplicationContext _context;
    public RecipeIngredientController(ApplicationContext context)
    {
        _context = context;
    }

    public IActionResult Index()
    {
        IEnumerable<RecipeIngredient> listOfrecipeIngredient = _context.RecipeIngredients;
        return View(listOfrecipeIngredient);
    }

    [HttpGet]
    public IActionResult Create()
    {
        // 页面初始化时加载下拉框数据
        ViewBag.listRecipes = _context.Recipes.Select(u => new SelectListItem 
        { 
            Text = u.Name, 
            Value = u.Id.ToString() 
        });
        ViewBag.listIngredients = _context.Ingredients.Select(u => new SelectListItem 
        { 
            Text = u.Name, 
            Value = u.Id.ToString() 
        });
        return View();
    }

    [HttpPost]
    public IActionResult Create(RecipeIngredient recipeIngredient)
    {
        if(ModelState.IsValid)
        {
            _context.RecipeIngredients.Add(recipeIngredient);
            _context.SaveChanges();
            return RedirectToAction("Index");
        }
        // 验证失败时重新加载下拉数据,返回创建视图并保留用户输入
        ViewBag.listRecipes = _context.Recipes.Select(u => new SelectListItem 
        { 
            Text = u.Name, 
            Value = u.Id.ToString() 
        });
        ViewBag.listIngredients = _context.Ingredients.Select(u => new SelectListItem 
        { 
            Text = u.Name, 
            Value = u.Id.ToString() 
        });
        return View(recipeIngredient);
    }
}

对应视图示例(Create.cshtml)

@model RecipeIngredient

<form asp-action="Create">
    <div class="form-group">
        <label asp-for="RecipeId" class="control-label">食谱</label>
        <select asp-for="RecipeId" asp-items="@ViewBag.listRecipes" class="form-control">
            <option value="">请选择食谱</option>
        </select>
        <span asp-validation-for="RecipeId" class="text-danger"></span>
    </div>

    <div class="form-group">
        <label asp-for="IngredientId" class="control-label">食材</label>
        <select asp-for="IngredientId" asp-items="@ViewBag.listIngredients" class="form-control">
            <option value="">请选择食材</option>
        </select>
        <span asp-validation-for="IngredientId" class="text-danger"></span>
    </div>

    <div class="form-group">
        <input type="submit" value="创建" class="btn btn-primary" />
    </div>
</form>

额外注意事项

  • 数据库数据检查:确认Recipes和Ingredients表中存在有效数据,避免因数据库为空导致下拉框无选项。
  • 添加必填验证:可在RecipeIngredient类的RecipeId和IngredientId属性上添加[Required]特性,确保用户必须选择选项:
    public class RecipeIngredient
    {
        public int Id { get; set; }
        [Required]
        public int IngredientId { get; set; }
        public Ingredient Ingredient { get; set; }
        [Required]
        public int RecipeId { get; set; }
        public Recipe Recipe { get; set; }
    }
    

内容的提问来源于stack exchange,提问作者Marcus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 10:32:05