c# - 在创建模式 MVC 4 中填充 DropDownList 中的数据

标签 c# asp.net asp.net-mvc entity-framework asp.net-mvc-4

我正在尝试使用 MVC4 从 DropDownList 中的表中填充数据。想弄清楚如何在编辑模式下将所有语言的标题放入下拉列表中。

模型:

public class CategoryLanguage
    {
        public int ID { get; set; }
        public int LanguageID { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
    }

public class Language
    {
        public int ID { get; set; }
        public string Title { get; set; }
    }

Controller :

public ActionResult Create()
        {
            using (MyDBContext db = new MyDBContext())
            {
                ViewBag.ID = new SelectList(db.Languages, "ID", "Title");
                return View();
            }
        }

        //
        // POST: /Emp/Create

        [HttpPost]
        public ActionResult Create(CategoryLanguage newCatLang)
        {
            using (MyDBContext db = new MyDBContext())
            {
                if (ModelState.IsValid)
                {
                    db.CategoryLanguages.Add(newCatLang);
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }

                ViewBag.ID = new SelectList(db.Languages, "ID", "Title", newCatLang.LanguageID);
                return View(newCatLang);
            }
        }

查看:

@model MultilanguageCategories.CORE.Models.CategoryLanguage

@{
    ViewBag.Title = "Create";
}

<h2>Add New Item</h2>

@using (Html.BeginForm())
{
        @Html.ValidationSummary(true)

        @Html.DropDownList("ID", "--Select--")
}

试图弄清楚如何在创建新的 CategoryLanguage 实体时将所有语言的标题放入 DropDown 中。错误显示:“操作无法完成,因为 DbContext 已被释放。”此行标记为:@Html.DropDownList("ID", "--Select--")

最佳答案

如下所述更改您的获取方法“创建”:

public ActionResult Create()
{
    var languages = new List<Language>();
    using (MyDBContext db = new MyDBContext())
    {
        languages = db.Languages.ToList();
    }

    ViewBag.ID = new SelectList(languages, "ID", "Title");
    return View();
}

现在您可以使用 DropDownListFor 如下所述:

@Html.DropDownListFor(model => model.[PropertyName], (IEnumerable<SelectListItem>)ViewBag.ID)

关于c# - 在创建模式 MVC 4 中填充 DropDownList 中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21478402/

相关文章:

c# - 如何在 Silverlight 中创建客户端帮助程序类?

c# - 使用 TimeSpan.Parse 的 QueryExtender Linq Orderby

c# - 在 C# 中使用 Lua 的最有效方法是什么?

asp.net - 在 ASP.NET 属性中组合字符串

c# - 只需要 'most recent' 任务 - 取消/忽略的最佳实践?

asp.net MVC 解决方案/项目布局

javascript - jQuery 添加类 onClick

asp.net-mvc - 在 ASP.NET MVC 项目和 Cordova 项目之间共享代码

asp.net-mvc - 带区域的 Url.Action() 返回空字符串

c# - 在 asp mvc 4 中发送带有空字段的 @html.beginform 时处理异常