Edit MVC with Foreign Key

3

I need to improve on my editLivros , then I'll explain my project.

Autores
-------
IdAutor
Nome

Livros
--------
IdLivro
Nome
IdAutor

I am registering the Authors and Books correctly, when I register the Livro , I make a ViewBag for the list of authors:

LivrosController to get Authors:

ViewBag.IdAutor = new SelectList(db.Autores, "IdAutor", "Nome");

% of% of Authors in DropDown Books:

@Html.DropDownList("IdAutor", ViewBag.IdAutor as SelectList, new { @class = "form-control" })

Model Books

    public partial class Livros
{
    [Key]
    public int IdLivro { get; set; }

    [Required]
    [StringLength(50)]
    public string Nome { get; set; }

    public int IdAutor { get; set; }

    public virtual Autores Autores { get; set; }

}

Model authors

    public partial class Autores
{
    [Key]
    public int IdAutor { get; set; }

    [StringLength(50)]
    public string Nome { get; set; }
}

Problem:

My problem is when I edit the book, automatically View Create takes the Visual Studio of the book and the Nome of the book, however, I needed to generate IdAutor with the authors, yes yes edit the author of the book, passing the IdAutor of the model dropbox

Thank you.

    
asked by anonymous 19.11.2015 / 19:04

2 answers

1

No Edit of LivrosController :

ViewBag.listaAutores = db.Autores;

In View of Livros :

@Html.DropDownListFor(model => model.IdAutor, ((IEnumerable<MVCCodeFirst.Models.Autores>)ViewBag.listaAutores).Select(option => new SelectListItem
{
    Text = option.Nome,
    Value = option.IdAutor.ToString(),
    Selected = (Model != null) && (Model.IdAutor == option.IdAutor)
}), "Selecione...", new { @class = "form-control" })
    
19.11.2015 / 19:28
5

Well, just keep doing what you're doing. Sending ViewBag with SelectList to View Create Books, but in this case you will already send a selected value.

When you create a SelectList , you can point the item to be selected as a parameter ( details ). So when you get to your View, your DropDownList will display all available items, but will leave the indicated item checked.

Your code looks like this:

ViewBag.IdAutor = new SelectList(db.Autores, "IdAutor", "Nome", Livro.IdAutor);

There is also the possibility to do as in the answer @Randrade posted in comments , the which only changes the context.

    
19.11.2015 / 19:23