Como resolver o erro: InvalidOperationException was unhandled by user code
20/05/2016
0
Bom dia, estou tentando fazer insert e está dando esse erro:
InvalidOperationException was unhandled by user code
An exception of type 'System.InvalidOperationException' occurred in System.Web.Mvc.dll but was not handled in user code
Additional information: The ViewData item that has the key 'IDArea' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'.
Esse comando estava funcionando e parou de repente, eu já recriei a view mais o erro continua. O comando de update está funcionando... na view ele marca esse trecho:
meu controller está assim:
[code
]//Adicionar
public ActionResult Adicionar()
{
ViewBag.IDArea = new SelectList(db.Areas, "IDArea", "Nome");
ViewBag.IDCargo = new SelectList(db.Cargos, "IDCargo", "Nome");
ViewBag.IDEmpregador = new SelectList(db.Empregadores, "IDEmpregador", "Nome");
return View();
}
[HttpPost]
public ActionResult Adicionar(Funcionarios funcionario, Eventos evento)
{
if (ModelState.IsValid)
{
funcionario.StatusFunc = "Ativo";
funcionario.UltimaAtualizacao = DateTime.Now;
db.Funcionarios.Add(funcionario);
db.SaveChanges();
//alimenta tabela Eventos
var pegaID = db.Funcionarios.First(x => x.Registro == funcionario.Registro);
evento.IDTipoDeEvento = 5; //5 = Admissão
evento.IDFuncionario = pegaID.IDFuncionario;
evento.NovoValor = "Ativo";
evento.DataAlteracao = DateTime.Now;
db.Eventos.Add(evento);
db.SaveChanges();
return RedirectToAction("FuncionariosAtivos");
}
return View(funcionario);
}
[/code]
No update os DropDownList funcionam normalmente...
A única coisa que fiz, foi instalar o jquery via package manage console, pois ele não está aceitando as datas no padrão do brasil (dd/mm/aaaa) ele quer as datas no padrão (mm/dd/aaaa), mesmo eu tendo adicionado o padrão que eu quero no model.
Alguém pode me ajudar? na outra vez que deu isso eu tive que refazer o projeto todo.... mas isso não é uma boa solução....
Obrigado.
InvalidOperationException was unhandled by user code
An exception of type 'System.InvalidOperationException' occurred in System.Web.Mvc.dll but was not handled in user code
Additional information: The ViewData item that has the key 'IDArea' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'.
Esse comando estava funcionando e parou de repente, eu já recriei a view mais o erro continua. O comando de update está funcionando... na view ele marca esse trecho:
Erro de Origem: Linha 51: @Html.LabelFor(model => model.IDArea, "IDArea", htmlAttributes: new { @class = "control-label col-md-2" }) Linha 52: <div class="col-md-10"> Linha 53: @Html.DropDownList("IDArea", null, htmlAttributes: new { @class = "form-control" }) Linha 54: @Html.ValidationMessageFor(model => model.IDArea, "", new { @class = "text-danger" }) Linha 55: </div>
meu controller está assim:
[code
]//Adicionar
public ActionResult Adicionar()
{
ViewBag.IDArea = new SelectList(db.Areas, "IDArea", "Nome");
ViewBag.IDCargo = new SelectList(db.Cargos, "IDCargo", "Nome");
ViewBag.IDEmpregador = new SelectList(db.Empregadores, "IDEmpregador", "Nome");
return View();
}
[HttpPost]
public ActionResult Adicionar(Funcionarios funcionario, Eventos evento)
{
if (ModelState.IsValid)
{
funcionario.StatusFunc = "Ativo";
funcionario.UltimaAtualizacao = DateTime.Now;
db.Funcionarios.Add(funcionario);
db.SaveChanges();
//alimenta tabela Eventos
var pegaID = db.Funcionarios.First(x => x.Registro == funcionario.Registro);
evento.IDTipoDeEvento = 5; //5 = Admissão
evento.IDFuncionario = pegaID.IDFuncionario;
evento.NovoValor = "Ativo";
evento.DataAlteracao = DateTime.Now;
db.Eventos.Add(evento);
db.SaveChanges();
return RedirectToAction("FuncionariosAtivos");
}
return View(funcionario);
}
[/code]
No update os DropDownList funcionam normalmente...
A única coisa que fiz, foi instalar o jquery via package manage console, pois ele não está aceitando as datas no padrão do brasil (dd/mm/aaaa) ele quer as datas no padrão (mm/dd/aaaa), mesmo eu tendo adicionado o padrão que eu quero no model.
Alguém pode me ajudar? na outra vez que deu isso eu tive que refazer o projeto todo.... mas isso não é uma boa solução....
Obrigado.
Ricardo
Curtir tópico
+ 0
Responder
Posts
20/05/2016
Ricardo
Encontrei o erro.... mas estou achando estranho... o erro está em um expressão regular que eu coloquei no modelo, a expressão verifica se a data foi digitada corretamente...
segue o o código completo da minha classe de modelo de funcionário, muita coisa não está funcionando ai, não sei por que....
[RegularExpression((@"^((0[1-9]|[12]\d)\/(0[1-9]|1[0-2])|30\/(0[13-9]|1[0-2])|31\/(0[13578]|1[02]))\/\d$"), ErrorMessage = "Data invalida")]
segue o o código completo da minha classe de modelo de funcionário, muita coisa não está funcionando ai, não sei por que....
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; namespace AppFuncionarios.Models { [MetadataType(typeof(FuncionariosMetadados))] public partial class Funcionarios { } public class FuncionariosMetadados { [Required(ErrorMessage = "Campo obrigatório")] //[RegularExpression("^([a-zA-Z0-9 .&'-]+)$", ErrorMessage = "Name invalido")] public string Nome { get; set; } public Nullable<int> Registro { get; set; } public int Ramal { get; set; } //[Display(Name = "Nascimento")] //[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")] //[DataType(DataType.Date, ErrorMessage = "Data em formato inválido")] //public Nullable<System.DateTime> DTNasc { get; set; } [Display(Name = "Nascimento")] [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")] //[RegularExpression((@"^((0[1-9]|[12]\d)\/(0[1-9]|1[0-2])|30\/(0[13-9]|1[0-2])|31\/(0[13578]|1[02]))\/\d$"), ErrorMessage = "Data invalida")] //[DataType(DataType.Date, ErrorMessage = "Data em formato inválido")] public Nullable<System.DateTime> DTNasc { get; set; } [Display(Name = "Área")] public Nullable<int> IDArea { get; set; } [Display(Name = "Cargo")] public Nullable<int> IDCargo { get; set; } [Display(Name = "Empregador")] public Nullable<int> IDEmpregador { get; set; } [Display(Name = "Adimissão")] [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")] //[DataType(DataType.Date, ErrorMessage = "Data em formato inválido")] public Nullable<System.DateTime> DTAdmissao { get; set; } [Display(Name = "Entrada")] public Nullable<System.TimeSpan> HrEntra { get; set; } [Display(Name = "Saída")] public Nullable<System.TimeSpan> Hrsai { get; set; } [Display(Name = "Status")] public string StatusFunc { get; set; } [Display(Name = "Demissão")] [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")] //[DataType(DataType.Date, ErrorMessage = "Data em formato inválido")] public Nullable<System.DateTime> DataDesligamento { get; set; } [Display(Name = "Atualizado")] [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")] public Nullable<System.DateTime> UltimaAtualizacao { get; set; } [Display(Name = "Tipo")] public string TipoFunc { get; set; } //[InputMask("99.999.999/9999-99")] public string CPF { get; set; } } }
Responder
Clique aqui para fazer login e interagir na Comunidade :)