How to put a dropdownlist in a cshtml

Asked

Viewed 615 times

-2

I need to place a dropdownlist under the following conditions: It will display the name of the City(City Table), but will only record the Employee Code. Using this approach, I can assemble the Dropdownlist: Model

public class Cidade
    {
        [Key]
        public int id { get; set; }
        [Required(ErrorMessage = "O nome da cidade é obrigatório", AllowEmptyStrings = false)]
        [Display(Name="Nome")]
        public String nome { get; set; }

        public List<Cidade> ListaCidades()
        {
            return new List<Cidade>   
            {
                new Cidade { id = 1, nome = "SÃO PAULO"}  
            }; 
        }
    }

See that my model is done manually. I could not bring the data directly from the table. In the controller I did so(Before I was using in Wrong Action):

public async Task<ActionResult> Index()
        {
            GetFuncionariosAsync funcionarios = new GetFuncionariosAsync();

            //popular a dropdown de cidades na view funcionarios
            GetCidadesAsync cidade = new GetCidadesAsync();
            var _cidade = await cidade.GetCidades();
            ViewBag.ViewCidade = new SelectList(_cidade, "id", "nome");

            var model = await funcionarios.GetFuncionarios(); 

            return View(model);
        }

        // GET: GetFuncionarios/Create
        public ActionResult Create(Cidade cidade)
        {
            var cidadeId = cidade.id;

            ViewBag.ViewCidade = new SelectList
            (
                new Cidade().ListaCidades(),
                "id",
                "nome",
                cidadeId
            );
            return View();
        }

and of course my cshtml (only the dropdownlist) was like this:

<div class="form-group">
        @Html.LabelFor(model => model.cidade, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
             @Html.DropDownList("id", (SelectList)ViewBag.ViewCidade, "- Selecione -", new { @class = "form-control" })
        </div>
    </div>

See the screenshot below of how the dropdown looks, now I just need to know how I load the list of the database and if I really need to create the Listings() method in the model? inserir a descrição da imagem aqui

See that in the dropdown, I show the City of São Paulo. But this was launched manually, now how I list the fields of the comic? Do I need the listicities() method? I find it unnecessary.

The way it is, if I try to do it that way,

public async Task<ActionResult> Create()
        {
            //var cidadeId = cidade.id;
            GetCidadesAsync cidade = new GetCidadesAsync();
            var _cidade = await cidade.GetCidades();
            ViewBag.ViewCidade = _cidade.Select(s => new SelectListItem { Value = s.id.ToString(), Text = s.nome });
            return View();
        }

I take the error below:

System.Invalidcastexception: 'Unable to cast Object of type 'Whereselectlistiterator`2[Trainingcrud.Models.City,System.Web.Mvc.Selectlistitem]' to type 'System.Web.Mvc.Selectlist'.'

Any help is welcome.

  • You must have a view model that includes City and Employees or can popular the Cities of DropDownList in his Controller and move on to the View in a ViewBag, remembering to already pass the selected item in the case of the edit screen.

  • If you create a SelectList in Controller and pass the ViewBag will make your job a lot easier. Do a search with these tips and if you can’t implement let me know that I put a response with the code.

  • No, it will not, follow the instructions I left in the comment. Ps. when I spoke at Controller I was referring to the Web project, not the API and the GET method

  • The problem is not only in View, it comes from the structure, for today follow the steps I gave you and if you can not solve or understand the problem let me know, tomorrow will be solved. Ps.: Post the GET action of your web project, for now forget the post and your API

  • Did you do this in the POST or GET action of create? "Avoid Edit 2" update the displayed code as you change it.

2 answers

1

You need to specify that your ViewCidade is a SelectList in the DropDownList.

@Html.DropDownList("Id", (SelectList)ViewBag.ViewCidade, "- Selecione -", new { @class = "form-control" })

See an example working here on dotnetfiddle

  • Same error. Return is a City List: List<City>, Can it go well? Who is it Id

  • No, see the example here: https://dotnetfiddle.net/yrj5Xx it is also a List<City>. The problem is certainly in your list. Look at the debug as it is coming. It comes id and name?

  • Id is the Id of the list cities that will be sent via post and would link (bind) to your model.

  • So I debugged now and in Viewcidade I have the 25 items. Viewcidade values are in Items. This says something?

  • No. See this screenshot: https://image.ibb.co/hkiogU/Capturar.png. . This is what your debug looks like?

  • Yes, only with 25 and not 1 like yours. As I am in the Create view, I don’t have a Return View(new City()) but a redirect to index

Show 2 more comments

-3

public async Task<ActionResult> Create()
        {
            GetCidadesAsync cidade = new GetCidadesAsync();
            var _cidade = await cidade.GetCidades();

            ViewBag.ViewCidade = new SelectList
            (
                _cidade,
                "id",
                "nome"
            );   
            return View();
        }

and in cshtml

<div class="form-group">
        @Html.LabelFor(model => model.cidade, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("cidade", (SelectList)ViewBag.ViewCidade, "- Selecione -", new { @class = "form-control" })
        </div>
    </div>

Browser other questions tagged

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