1
ASP.NET MVC4
I’m having a data return problem of a dropdownlist where the same list correctly values, but when choosing some value and post on the page the value arrives as null in the controller.
my Dominio is like this: Table of Contents
namespace VelhosAmigos.WebSite.Dominio.Entidade
{
    public class Conteudo
    {
        [Key]
        [HiddenInput(DisplayValue = false)]
        public int IdConteudo {get; set;}
        [Required(ErrorMessage = "Digite um Título")]
        [Display(Name = "Título: ")]
        [StringLength(150, ErrorMessage = "O Título da publicação não pode ter mais que 150 caracteres.")]
        [Description("Teste de descrição")]
        public string Titulo { get; set; }
        [Required(ErrorMessage = "Digite um Conteúdo para exibição")]
        [Display(Name = "Conteúdo completo: ")]
        [DataType(DataType.MultilineText)]
        public string txt_Conteudo { get; set; }
        //[Required(ErrorMessage = "Escolha uma categoria")]
        [Display(Name = "Categoria: ")]
        public virtual Categoria Categoria { get; set; }And the Categories table:
namespace VelhosAmigos.WebSite.Dominio.Entidade
{
    public class Categoria
    {
        [Key]
        public int IdCategoria { get; set; }
        public string NomeCategoria { get; set; }
        public int IdSessao { get; set; }
        
    }
}In the Category repository I have a list of all categories:
namespace VelhosAmigos.WebSite.Dominio.Repositorio
{
    public class CategoriasRepositorio
    {
        private readonly EFDbContext _context = new EFDbContext();
        public IEnumerable<Categoria> Categorias
        {
            get { return _context.Categorias; }
        }
        public List<Categoria> retornarTodas()
        {
            var categorias = (from c in _context.Categorias
                              select c).ToList();
            return categorias;
        }
    }
}And in the controller, I have a ViewBag that passes all categories registered in the database to be used as Dropdownlist the creation or modification of new content.
       public ViewResult Alterar(int IdConteudo)
        {
            _repositorio = new ConteudosRepositorio();
            Conteudo conteudo = _repositorio.Conteudos
                .FirstOrDefault(c => c.IdConteudo == IdConteudo);
            var _categRepositorio = new CategoriasRepositorio().retornarTodas();
            ViewBag.Categorias = _categRepositorio;
          
            return View(conteudo);
        }In the View Alter have the Dropdownlist which generates the right data, just add an empty option at the beginning with the Select a Category option that I still can’t do either.
@Html.DropDownListFor(c => c.Categoria, new SelectList(@ViewBag.Categorias, "IdCategoria", "NomeCategoria"), new { @class = "form-control" })The result of this Dropdownlist is apparently correct:
<select name="Categoria" id="Categoria" class="form-control">
  <option value="1">Fique por Dentro</option>
<option value="2">Artigos</option>
</select>But when choosing an option and filling the other requirements of the form and submitting the data... on HttpPost of controler:
[HttpPost]
        public ActionResult Alterar(Conteudo conteudo)
        {
            var _categRepositorio = new CategoriasRepositorio().retornarTodas();
            ViewBag.Categorias = _categRepositorio;
            if (ModelState.IsValid)
            {
                if (conteudo.IdConteudo > 0)
                {
                    TempData["mensagem"] = string.Format("{0} foi alterado com sucesso!", conteudo.Titulo);
                }
                else 
                {
                    TempData["mensagem"] = string.Format("{0} foi cadastrado com sucesso!", conteudo.Titulo);
                }
                _repositorio = new ConteudosRepositorio();
                _repositorio.Salvar(conteudo);
                
                return RedirectToAction("Listar");
            };
            
            return View(conteudo);
        }Is returning as NULL the value of the Category. ai returns to the page with the reset listing and the error below the field:
<span data-valmsg-replace="true" data-valmsg-for="Categoria" class="field-validation-error">The value '1' is invalid.</span>
In the SQL Server, the Category field is listed as int, and if I manually register at the bank the listView displays the contents registered correctly.