[英]Simple Dropdownlist from a simple model with MVC4
我有一個簡單的模型:
public partial class Entidade
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Nome { get; set; }
public virtual Pais Pais { get; set; }
}
與Pais模型有關:
public partial class Pais
{
public Pais()
{
this.Entidades = new HashSet<Entidade>();
}
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Nome { get; set; }
public virtual ICollection<Entidade> Entidades { get; set; }
}
我需要構建一個簡單的Pais下拉列表來創建新的Entidade:
<div class="editor-label">
@Html.LabelFor(model => model.Pais, "Pais")
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.Pais, ViewBag.Paises as SelectList)
@Html.ValidationMessageFor(model => model.Pais)
</div>
從控制器:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Entidade entidade)
{
if (ModelState.IsValid)
{
db.Entidades.Add(entidade);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.Paises = new SelectList(db.Paises, "Id", "Nome");
return View(entidade);
}
但是我得到了錯誤:
There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'Pais'.
任何想法?
謝謝
您不是為Id而是為Pais實體創建下拉列表,因此:
@Html.DropDownListFor(model => model.Pais.Id, ViewBag.Paises as SelectList)
但是,如果您沒有將模型Pais屬性設置為實例,則將最終導致NullReferenceException。
其他提示:如果可以嘗試避免使用ViewBag或ViewData。 在這種情況下,您可以創建一個甚至從Entidade派生的EntidadeViewModel類,並且該類可以具有IEnumerable類型的屬性。 這樣,您的代碼將更具可讀性和一致性。
嘗試
ViewBag.Paises = db.Paises.ToList();
@Html.DropDownList("Id",new SelectList(ViewBag.Paises,"Id","Nome"))
像這樣做:
佩斯
public Pais()
{
Entidades = new HashSet<Entidade>();
}
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Nome { get; set; }
public virtual ICollection<Entidade> Entidades { get; set; }
Entidade.cs
public class Entidade
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Nome { get; set; }
[ForeignKey("Pais")]
public int PaisId { get; set; }
public virtual Pais Pais { get; set; }
}
EntidateController.cs
//GET: /Entidade/Create
public ActionResult Create()
{
ViewBag.PaisId = new SelectList(db.Paises, "Id", "Nome");
return View();
}
// POST: /Entidade/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Entidade entidade)
{
if (ModelState.IsValid)
{
db.Entidades.Add(entidade);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.PaisId = new SelectList(db.Paises, "Id", "Nome", entidade.PaisId);
return View(entidade);
}
停止Create.cshtml
@Html.DropDownList("PaisId", String.Empty)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.