none
DropDownList - Razor MVC3

    Question

  • Oi pessoal cá estou eu apanhando do mvc 3 mais um pouquinho...rsr

     

    Eu tinha feito uma dropdownlistfor em uma outra tela só pra testar. Mas agora que coloquei na que realmente preciso fica me dando esse erro: There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'Nome'. sendo que ao meu ver tem...

    Eu tenho a Model

     public class MontarGradeModels
        {
            #region Propriedades
            [DisplayName("Nome")]
            public string Nome { get; set; }
    
            [DisplayName("Id")]
            public int Id { get; set; }
    
            #endregion
        }


    A Controller:

    public ActionResult SelecionarTurmas(IEnumerable<TurmaGradeModel> model, FormCollection collection)
            {
                IProcessoMontarGradeNegocios processoMontarGradeNegocios = FabricaNegocios.ProcessoMontarGradeNegocios(Sessao.Usuario.Unidade, Sessao.ProcessoMontarGrade);
                processoMontarGradeNegocios.SelecionarTurmas(from t in model
                                                             where t.Selecionada
                                                             select t.TurmaGrade);
                processoMontarGradeNegocios.MontarGrade();
    
    
                IEnumerable<Professor> professor = FabricaNegocios.ProfessorNegocios().Listar();
    
                ViewData["ProfessorList"] = new SelectList(professor, "Id", "Nome");
    
    
                return RedirectToAction("ConfirmarGrade");
            }


    E a View:

    @using Controle_de_Grade.Lib.Basico;
    @using Controle_de_Grade.Lib.Negocios;
    @using Controle_de_Grade.Lib.Dados;
    @using Controle_de_Grade.Util;
    @using Controle_de_Grade.Models;
    @model IEnumerable<TurmaGrade>
    
    
        @foreach (TurmaGrade turmaGrade in Model)
        {
            <tr>
                <td>@Html.Partial("~/Views/Curso/Link.cshtml", turmaGrade.Turma.Modulo.Curso)
                </td>
                <td>@Html.Partial("~/Views/Modulo/Link.cshtml", turmaGrade.Turma.Modulo)
                </td>
                <td>@Html.Partial("~/Views/Turma/Link.cshtml", turmaGrade.Turma)
                </td>
                <td>@turmaGrade.Turma.Turno.EnumToString()
                </td>
                <td>
                    @turmaGrade.Turma.Distribuicao.EnumToString()
                    @if (turmaGrade.Turma.Distribuicao == Turma.EDistribuicao.DiaAlternado)
                    {
                        @String.Format("({0})", turmaGrade.Turma.DistribuicaoHorario.EnumToString())
                    }
                </td>
                <td>@String.Format("{0:dd/MM/yyyy}", turmaGrade.DataInicial)
                </td>
                <td>@String.Format("{0:dd/MM/yyyy}", turmaGrade.DataFinal)
                </td>
            </tr>
            <tr>
                <td colspan="7">
                    <table>
                        <th>
                            Disciplina
                        </th>
                        <th>
                            Professor
                        </th>
                        <th>
                            Local de Aula
                        </th>
                        <th>
                            Data Inicial
                        </th>
                        <th>
                            Data Final
                        </th>
                        <th>
                            Horários
                        </th>
                        @foreach (DisciplinaGrade disciplinaGrade in FabricaNegocios.DisciplinaGradeNegocios(turmaGrade).Listar())
                        {   
                            <tr>
                                <td>@Html.Partial("~/Views/Disciplina/Link.cshtml", disciplinaGrade.Disciplina)
                                </td>
    
                                <td>@Html.DropDownList("Name", (IEnumerable<SelectListItem>)ViewData["ProfessorList"])</td>
                                
                                @*<td>
                                    @Html.Partial("~/Views/Professor/Link.cshtml", disciplinaGrade.Professor ?? new Professor())
                                </td>*@
                                <td>
                                </td>
                                <td>@Html.Partial("~/Views/LocalAula/Link.cshtml", disciplinaGrade.LocalAula ?? new LocalAula())
                                </td>
                                <td>@String.Format("{0:dd/MM/yyyy}", disciplinaGrade.DataInicial)
                                </td>...


    Percebi que ao tentar usar o DropDownListFor (model => model.Nome..... ele não deixa pois estou usando @model IEnumerable e não @model MinhaModel. Aí mudei entao para DropDownList e fica dando esse erro.

    Não sei porque ele tá reclamando tanto desse "Nome", sendo que o que ele espera ali é uma string Name que nada mais é do que the name of the formfield to return.

     

    Bom se alguém der uma luz, agradeço!

     

     

     

     


    Alessandra Regina
    Monday, February 06, 2012 8:07 PM

Answers

  • Well...

    I did it!But I don´t know if is the right way.

    I just put the code

    IEnumerable<Professor> professor = FabricaNegocios.ProfessorNegocios().Listar().OrderBy(x => x.Nome);   

    ViewData["ProfessorList"] = professor.Select(x => new SelectListItem { Text = x.Nome, Value = x.Id.ToString() });

    in the view and it works!Now he founds the ViewData. I know that is not a good programming practice.


    Alessandra Regina

    • Marked as answer by MSPAlessandra Thursday, February 09, 2012 2:10 PM
    Tuesday, February 07, 2012 1:12 PM

All replies

  • I only speak English, but I think I see the problem in your code.

    ViewData["ProfessorList"] = new SelectList(professor, "Id", "Nome");
    


    Try this instead:

    using System.Linq;
    
    ViewData["ProfessorList"] = professor.Select(x => new SelectListItem { Text = x.Nome, Id = x.Id });


    Check out My Blog. Now updated to actually work!
    Monday, February 06, 2012 8:52 PM
  • Hi Tim

     

    Thanks for your answer but doesn´t work yet. It stays saying that There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'Nome.

    I still putting "Nome" in the firs parameter of DropDown(...Is correct?

    Alessandra Regina
    Monday, February 06, 2012 9:02 PM
  • The first parameter is just the name of the dropdown element in the rendered HTML. It doesn't really matter what you put in there. The rest looks like it should work.

    I overlooked it the first time, but the real issue is that you are calling RedirectToAction, which clears the ViewData dictionary. ViewData only lasts for the scope of the current MVC action and the rendering of the view. If you redirect to another action, you have a whole new ViewData dictionary. The same goes for ViewBag.

    You may be able to use TempData instead of ViewData, but then you would have to copy the select list items from TempData to ViewData in the ConfirmarGrade action.


    Check out My Blog. Now updated to actually work!
    Monday, February 06, 2012 9:16 PM
  • Hi Alessandra,

    Could you please translate the post in English so that you may get more and better responses?

    Thanks for your posting and understanding.


    Paul Zhou [MSFT]
    MSDN Community Support | Feedback to us

    Tuesday, February 07, 2012 3:22 AM
  • Yes,

    Please translate your requiremets in English

    http://www.java-forums.org/forum.php
    Tuesday, February 07, 2012 5:30 AM
  • Hi people sorry about my English ok?

    I had madeadropdownlistforonanother screenjust totest.But nowthat I put inthat I really needisgiving methis error: There isinViewDataitemof type'IEnumerable<SelectListItem>'that has thekey'name'.

    I realized thattrying to use theDropDownListFor(model =>model.Nome.....he did notleavebecause I'musing@IEnumerableand not@modelMyModel.SothenI changedtoDropDownListand isgivingthis error.

    Do not know whyhe'scomplaininga lot that"Name", andthathe hopesthereisastringname thatis nothing morethanthe name oftheformfieldto return.

    The codes is the same of the first post below. I tried what the Tim says to do, but doesn´t work.

    Now,I'll try toget thecode outside theblockActionResult.


    Alessandra Regina

    Tuesday, February 07, 2012 12:22 PM
  • Well...

    I did it!But I don´t know if is the right way.

    I just put the code

    IEnumerable<Professor> professor = FabricaNegocios.ProfessorNegocios().Listar().OrderBy(x => x.Nome);   

    ViewData["ProfessorList"] = professor.Select(x => new SelectListItem { Text = x.Nome, Value = x.Id.ToString() });

    in the view and it works!Now he founds the ViewData. I know that is not a good programming practice.


    Alessandra Regina

    • Marked as answer by MSPAlessandra Thursday, February 09, 2012 2:10 PM
    Tuesday, February 07, 2012 1:12 PM