Validation for Dropdownlist in ASP.NET MVC

Asked

Viewed 29 times

0

I’m doing a project, I was doing a Dropdownlist that takes the database data and shows the user. To some extent everything went well, but it lacks a part of treatment, or a validation, because every time some text box is blank, it for the application and gives this error

System.InvalidOperationException: 'O item ViewData que possui a chave 'idCategoria' é do tipo 'System.String', mas precisa ser do tipo 'IEnumerable<SelectListItem>'.'

This error always occurs when I pass one SelectList using a ViewBag

I have the following codes:

Model Produto

public class Produto
{
    private ConexaoDB db;

    [Display(Name = "Código")]
    [StringLength(5, ErrorMessage = "Máximo 5 caracteres")]
    [Key]
    public string idProduto { get; set; }

    [Display(Name = "Nome")]
    [Required(ErrorMessage = "O campo é obrigatório")]
    [StringLength(50, ErrorMessage = "Máximo 50 caracteres")]
    public string nome { get; set; }

    [Display(Name = "Preço Unitário")]
    [Required(ErrorMessage = "O campo é obrigatório")]
    public decimal precoUnitario { get; set; }

    [Display(Name = "Categoria")]
    [Required(ErrorMessage = "O campo é obrigatório")]
    public string idCategoria { get; set; }

    public IEnumerable<SelectListItem> CategoryList { get; set; }

 ...

    public List<Categoria> ListarCategoria()
{
    var strQuery = "select idCategoria, nome from categoria";

    using (db = new ConexaoDB())
    {
        var retorno = db.RetornaRegistro(strQuery);
        return ListaDeCategoria(retorno);
    }
}

public List<Categoria> ListaDeCategoria(MySqlDataReader retorno)
{
    var categorias = new List<Categoria>();
    while (retorno.Read())
    {
        var TempCategoria = new Categoria()
        {
            idCategoria = retorno["idCategoria"].ToString(),
            nome = retorno["nome"].ToString()
        };
        categorias.Add(TempCategoria);
    }
    return categorias;
}

...


}

Productocontroller

public ActionResult Create()
{
    var objproduto = new Produto();
    var leitor = objproduto.ListarCategoria();
    ViewBag.List = new SelectList(leitor, "idCategoria", "nome");
    return View();
}

// POST: Produto/Create
[HttpPost]
public ActionResult Create(Produto produto)
{
    if (ModelState.IsValid)
    {
        var objproduto = new Produto();
        objproduto.InsertProduto(produto);

        return RedirectToAction("Details");
    }
    return View(produto);
}

View

<div class="form-group">
    @Html.LabelFor(model => model.idCategoria, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownListFor(model => model.idCategoria, ViewBag.List as SelectList, "-- Selecione a categoria --", new { @required = "required", @class = "form-control" })
        @Html.ValidationMessageFor(model => model.idCategoria, "", new { @class = "text-danger" })
    </div>
</div>

How can I solve this problem?

  • Why do you put everything in the same class, the model part with the operations? Who taught you that way? If you knew this is wrong, unproductive, causes performance problems (performace), is your code cost high? Out of the pattern of names that is also in the wrong style

  • 1

    I really didn’t know it was wrong, it’s that I started using MVC a little while ago, and I’m still a little confused on how to use it. I’m trying to dig a little deeper into

  • The layers are separated, basically speaking: the entities/models that represent the information, another for database operations that use these entities ... this is the basics. Usually college teaches wrong ...

  • Right, so controllers are especially for requests? The methods should be in controllers?

  • Controller receive and return Verb request operations (GET, POST, PUT, DELETE) are like semaphores, database operations are ORM, Microorm, CRUD basic layers, and the classes that represent for example a database table are the logical models that represent the physical models (tables) ... Of course this is the basics. Everyone has his responsibility, when a class has more than one responsibility breaks one of the principles of OOP

  • Methods like this (Listarcategoria), where it would be the most appropriate place to put it?

  • In another example class class Dal { public List<Categoria> Lista(){ ...}}

  • this standard is repository with ORM: http://www.macoratti.net/14/04/mvc_crud.htm. although ORM Entity Framework is a repository layer. but show you the breakup

  • This one I really didn’t know, it gets much more organized clean, I’m going to do a better ORM. Actually the school doesn’t teach this

  • 1

    As you said, lack of organization is one of the biggest problems, and one of my mistakes occurred due to lack of organization. I’ve already made the mistake, and in future projects, I’ll start to organize myself more

Show 5 more comments
No answers

Browser other questions tagged

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