Error while trying to pass an ordered collection to a View

Asked

Viewed 141 times

3

I’m trying to get to the View an ordered collection, but I’m always having the same error:

There is no Viewdata item of type 'Ienumerable' that has the key 'Titulodecortesia'

The only way I can successfully run my code is by using the following line:

@Html.DropDownListFor(model => model.TituloDeCortesia, new SelectList(new[] { "Dr.", "Mr.", "Ms.", "Mrs." }), String.Empty)

However, no sorting. In this example I sorted manually, but in the case of larger and dynamic listings, this solution I found would not solve.

Follow my code below:

Controller

public ActionResult Adicionar()
{
    List< string > ListaTitulo = new List< string > { "Ms.", "Dr.", "Mrs.", "Mr." };
    ListaTitulo.Sort();
    ViewBag.TituloDeCortesia = new SelectList(ListaTitulo);
    return View();
}

View

@model MvcModeloEmpresa.Dominio.Empregado
@{
    ViewBag.Title = "Adicionar";
}

<h2>Adicionar</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Empregado</legend>
        @Html.HiddenFor(model => model.EmpregadoID)

        <div class="col-md-10">
            @Html.LabelFor(model => model.PrimeiroNome)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.PrimeiroNome)
            @Html.ValidationMessageFor(model => model.PrimeiroNome)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.UltimoNome)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.UltimoNome)
            @Html.ValidationMessageFor(model => model.UltimoNome)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Titulo)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Titulo)
            @Html.ValidationMessageFor(model => model.Titulo)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.TituloDeCortesia)
        </div>
        <div class="editor-field">
            @Html.DropDownList("TituloDeCortesia", String.Empty)
            @Html.ValidationMessageFor(model => model.TituloDeCortesia)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.DataNascimento)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.DataNascimento)
            @Html.ValidationMessageFor(model => model.DataNascimento)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.DataContratacao)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.DataContratacao)
            @Html.ValidationMessageFor(model => model.DataContratacao)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Endereco)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Endereco)
            @Html.ValidationMessageFor(model => model.Endereco)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Cidade)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Cidade)
            @Html.ValidationMessageFor(model => model.Cidade)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Regiao)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Regiao)
            @Html.ValidationMessageFor(model => model.Regiao)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.CodigoPostal)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.CodigoPostal)
            @Html.ValidationMessageFor(model => model.CodigoPostal)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Pais)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Pais)
            @Html.ValidationMessageFor(model => model.Pais)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.TelefoneResidencial)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.TelefoneResidencial)
            @Html.ValidationMessageFor(model => model.TelefoneResidencial)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Extensao)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Extensao)
            @Html.ValidationMessageFor(model => model.Extensao)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Notas)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Notas)
            @Html.ValidationMessageFor(model => model.Notas)
        </div>

        <p>
            <input type="submit" value="Salvar" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Voltar", "Index")
</div>

Error Presented inserir a descrição da imagem aqui

  • I tested your code here and it worked perfectly. You are entering the action Adicionar when threshing?

  • When I select an item and submit the data, I have the error of the image I entered at the end of my question.

  • Ask your question any and all information from controller traffic to view (Full code)

  • Cezar, do you want me to put all the code in my View? How do I see the traffic from my controller method?

  • As @Cezar said, your code is correct. Look at an example works here (https://dotnetfiddle.net/8wwRPR). What version of Asp.Net MVC are you using?

2 answers

2

These two forms as example below are correct:

@Html.DropDownList("TituloDeCortesia", String.Empty)
@Html.DropDownList("TituloDeCortesia", (SelectList)ViewBag.TituloDeCortesia)

That is, your code is correct by what is in question, what must be happening is another type of error of not passing the information correctly through Viewbag.

Another way

public ActionResult Adicionar()
{

    IList<SelectListItem> Lista = new List<SelectListItem>();

    Lista.Add(new SelectListItem() { Text = "Ms.", Value = "Ms." });
    Lista.Add(new SelectListItem() { Text = "Dr.", Value = "Dr." });
    Lista.Add(new SelectListItem() { Text = "Mrs.", Value = "Mrs." });
    Lista.Add(new SelectListItem() { Text = "Mr.", Value = "Mr." });

    ViewBag.ListaTitulo = Lista;

    return View();
}

View: (Only that stretch)

<div class="editor-label">
    @Html.Label("Titulo de Cortesia")
</div>
<div class="editor-field">
    @Html.DropDownListFor(m => Model.TituloDeCortesia, (IEnumerable<SelectListItem>)ViewBag.ListaTitulo)
    @Html.ValidationMessageFor(model => model.TituloDeCortesia)
</div>

Note that the Label I had to put directly in this case, please test!!!

  • Ceza, I’ve tried both ways and you have the same mistake.

  • @Kellysoares, you’re doing something wrong, I’d need to see in your question the whole view and your whole controller, anything else stick to www.pastebin.com

  • I edited my question by putting my complete View.

  • @Kellysoares put another way for you to test there please!

  • Cezar, still error like I was using a Viewdata trying to get a key: There is no Viewdata item of type 'Ienumerable<Selectlistitem>' that has the key 'Titulodecortesia'.

  • Really look at the particular problem, because all these forms are correct including @Randrade created an example: https://dotnetfiddle.net/8wwRPR and it works perfectly!!! Which version of your ASP.NET, Which Visual Studio is (2010, 2015) etc ... ?

  • I use Visual Studio 2013 and ASP.NET MVC 4.

  • Ceza, I edited my question right at the beginning. I entered a shape that I found to work the code, but I couldn’t put sorting. Does this form become easier to understand the problem or try to sort that list?

  • 1

    @Html.DropDownListFor(model => model.TituloDeCortesia, new SelectList(new[] { "Dr.", "Mr.", "Ms.", "Mrs." }.OrderBy(x => x).ToList()), String.Empty)

  • 1

    Cezar, it worked out. For now I’ll leave my question open to see if anyone can figure out the problem that isn’t working out by passing a collection through a controller method. Thanks for your help!

  • @Kellysoares, it looks like you will have to install the visual studio again or format your PC. Maybe this is it.

  • Ceza, analyzing my code I discovered the error, I typed my entire view without using Scaffolding, with this, the possibility of errors is a little bigger, what happened to me. When writing the code I ended up including the @Html.Hiddenfor(model => model.Empregadoid) line, this view is for entering data, so it is not necessary to use hidden fields.

Show 7 more comments

-1


i discovered the error in my code. I was using hidden field in a Data Insertion View that there is no need. Upon realizing the error and deleting, I was able to pass a collection directly through my controller method Add

@Html.HiddenFor(model => model.EmpregadoID)

  • There is no relation between sorting data in a view with a field hidden in your add method. Probably you expressed yourself badly in your question, where your answer does not solve the error.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.