简体   繁体   English

来自带有MVC4的简单模型的简单Dropdownlist

[英]Simple Dropdownlist from a simple model with MVC4

I have a simple Model: 我有一个简单的模型:

public partial class Entidade
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public string Nome { get; set; }

    public virtual Pais Pais { get; set; }
}

related with the Pais model: 与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; }
}

and I need to build a simple dropdown list of the Pais's to create a new Entidade: 我需要构建一个简单的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>

from the controller: 从控制器:

[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);
}

But I get the error: 但是我得到了错误:

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'Pais'.

Any idea? 任何想法?

Thanks 谢谢

You are creating adrop down for a Pais entity not for it's Id, so: 您不是为Id而是为Pais实体创建下拉列表,因此:

@Html.DropDownListFor(model => model.Pais.Id, ViewBag.Paises as SelectList)

But this will end up in a NullReferenceException if you aren't setting the model Pais property to an instance. 但是,如果您没有将模型Pais属性设置为实例,则将最终导致NullReferenceException。

Addtitional tip: if you can try avoid using ViewBag or ViewData. 其他提示:如果可以尝试避免使用ViewBag或ViewData。 In this sitiation you can create a EntidadeViewModel class even derived from Entidade and this can have a property of type IEnumerable. 在这种情况下,您可以创建一个甚至从Entidade派生的EntidadeViewModel类,并且该类可以具有IEnumerable类型的属性。 In this way your code will be more readable and consistent. 这样,您的代码将更具可读性和一致性。

Try 尝试

ViewBag.Paises = db.Paises.ToList();

@Html.DropDownList("Id",new SelectList(ViewBag.Paises,"Id","Nome"))

Do it like this: 像这样做:

Pais.cs 佩斯

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 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 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);
}

Entidate Create.cshtml 停止Create.cshtml

@Html.DropDownList("PaisId", String.Empty)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM