While performing a project I came across the following error:
System.InvalidOperationException: The parameter conversion from type 'System.String' to type 'RamalAguia.Models.Setor' failed because no type can convert between these types.
This is my Controller:
[HttpGet]
public ActionResult Create()
{
PreparaFormulario();
return View();
}
[HttpPost]
public ActionResult Create(RamalModel model)
{
if (ModelState.IsValid)
{
_db.Ramais.Add(model);
_db.SaveChanges();
return RedirectToAction("Index", new { id = model.ID });
}
else
{
PreparaFormulario();
return View();
}
}
[HttpGet]
public void PreparaFormulario()
{
var setores = new List<Setor>();
using (RamaDb db = new RamaDb())
{
setores = db.Setores.ToList();
}
ViewBag.ID2 = new SelectList(_db.Setores, "setorID", "setorNome");
}
A View:
@Html.DropDownListFor(model => model.setores, (SelectList)ViewBag.ID2)
And the Model:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace RamalAguia.Models
{
public class RamalModel
{
public int ID { get; set; }
[Required(ErrorMessage = "O nome é obrigatório.")]
public string Nome { get; set; }
[Required(ErrorMessage = "O número é obrigatório.")]
public int Numero { get; set; }
public Setor setores { get; set; }
How can I fix it?
Edit
Obs: I was able to find this error through a breakpoint in ModelState.IsValid, when the application will save the data passed, within the values I use to save the sector. >
Industry Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace RamalAguia.Models
{
public class Setor
{
public int setorID { get; set; }
public string setorNome { get; set; }
public Area areas { get; set; }
}
}
Edit2:
Classes:
RamalModel
public class RamalModel
{
public int ID { get; set; }
[Required(ErrorMessage = "O nome é obrigatório.")]
public string Nome { get; set; }
[Required(ErrorMessage = "O número é obrigatório.")]
public int Numero { get; set; }
public int SetorId { get; set; }
[ForeignKey("SetorId")]
public Setor setores { get; set; }
Sectors
public class Setor
{
public int setorID { get; set; }
public string setorNome { get; set; }
public Area areas { get; set; }
And dbcontext
namespace RamalAguia.Models
{
public class RamaDb : DbContext
{
public DbSet<Usuario> Usuarios { get; set; }
public DbSet<RamalModel> Ramais { get; set; }
public DbSet<Setor> Setores { get; set; }
public DbSet<Area> Areas { get; set; }
}
}