我正在尝试使用MVC4从DropDownList中的表填充数据。试图找出如何在编辑模式下将所有语言的标题放入DropDown。
型号:
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; }
}
控制器:
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 - ”)
答案 0 :(得分:3)
更改您的获取方法“创建”,如下所述:
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)
答案 1 :(得分:2)
你很亲密......
您需要将语言选择列表添加到viewbag(您已经完成,但命名错误的键)
ie:ViewBag.LanguagesList = new SelectList(db.Languages, "ID", "Title");
如果你想要一个很容易的空字段:
var langs = db.Languages.ToList().ConvertAll(x => new SelectListItem() { Value = x.ID, Text = x.Title });
langs.Insert(0, new SelectListItem() { Value = "", Text = "--Select--" });
ViewBag.LanguagesList = langs;
DropdownList应该是模型中的属性。
@Html.DropDownListFor(m => m.LanguageID, (IEnumerable<SelectListItem>)ViewBag.LanguagesList)
由于您看起来正在使用Entity Framework类作为模型,因此需要确保在呈现视图之前不处理上下文。
根据Microsoft的示例link实例化控制器顶部的上下文,并在Create方法中删除using语句。
即:
public class LanguageCategoryController : Controller
{
MyDBContext db = new MyDBContext();
public ActionResult Create()
{
ViewBag.LanguagesList = new SelectList(db.Languages, "ID", "Title");
// or replace the above line with the other example above
// if you want the empty "--select--" option
return View();
}
}