Usuário com melhor resposta
There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'CategId'.

Pergunta
-
Boa noite Pessoal
sou novo a programar em asp.net mvc, estou com dificuldades de cadastrar um formulário que contem duas dropdownlist, ele carrega na view mas quando clico no botão guardar vem este erro: There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'CategId'. fiz conforme aprendi, mas não sei de onde vem o erro abaixo esta o controller com a view
Model categoria
public class Categ { [Key] public int CategId { get; set; } [Display(Name = "Categoria")] [Required(ErrorMessage = "O campo {0} Precisa ser preenchido")] public string Nome { get; set; } }
Controller
public ActionResult Create() { ViewBag.CategList = new SelectList(db.Categs, "CategId", "Nome"); ViewBag.Gabinetes = new SelectList(db.Gabinetes, "GabineteId", "Nome"); return View(); } // POST: Pessoas/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create(PessoaView view) { if (ModelState.IsValid) { db.Pessoas.Add(view.Pessoa); try { if (view.Foto != null) { var pic = Utilidades.UploadPhto(view.Foto); if (!string.IsNullOrEmpty(pic)) { view.Pessoa.Photo = string.Format("~/Content/Fotos/{0}", pic); } } db.SaveChanges(); return RedirectToAction("Index"); } catch (Exception ex) { ModelState.AddModelError(string.Empty, ex.Message); } } return View(view); }
View
@model GesTark.Models.PessoaView @{ ViewBag.Title = "Create"; } <h2>Create</h2> @using (Html.BeginForm(Html.BeginForm("Create", "Pessoas", FormMethod.Post, new { enctype = "multipart/form-data" }))) { @Html.AntiForgeryToken() <div class="form-horizontal"> <h4>Pessoa</h4> <hr /> @Html.ValidationSummary(true, "", new { @class = "text-danger" }) <div class="form-group"> @Html.LabelFor(model => model.Foto, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> <span class="btn btn-default btn-file"> @Html.TextBoxFor(model => model.Foto, new { type = "file" }) </span> <br /> </div> <div class="form-group"> @Html.LabelFor(model => model.Pessoa.CategoriaId, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.DropDownList("CategId", ViewBag.CategList as IEnumerable <SelectListItem>, "Selecione uma Categoria") @Html.ValidationMessageFor(model => model.Pessoa.CategoriaId, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.Pessoa.Email, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.Pessoa.Email, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Pessoa.Email, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.Pessoa.GabineteId, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @*@Html.DropDownList("Gabinetes", ViewBag.Gabinetes as IEnumerable<SelectListItem>, "Selecione um Gabinete")*@ @Html.ValidationMessageFor(model => model.Pessoa.GabineteId, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Create" class="btn btn-default" /> </div> </div> </div> </div> }
Por favor alguma dica
- Editado GILBLAZER quinta-feira, 17 de maio de 2018 17:22
Respostas
-
testa ai
public ActionResult Create(PessoaView view) { //aqui ele vai preencher ele de novo ViewBag.CategList = new SelectList(db.Categs, "CategId", "Nome"); if (ModelState.IsValid) { db.Pessoas.Add(view.Pessoa); try { if (view.Foto != null) { var pic = Utilidades.UploadPhto(view.Foto); if (!string.IsNullOrEmpty(pic)) { view.Pessoa.Photo = string.Format("~/Content/Fotos/{0}", pic); } } db.SaveChanges(); return RedirectToAction("Index"); } catch (Exception ex) { ModelState.AddModelError(string.Empty, ex.Message); } } return View(view); }
- Marcado como Resposta GILBLAZER sexta-feira, 18 de maio de 2018 21:05
Todas as Respostas
-
oi,
Na requisição ele perde os valores do campo. na sua controle create você precisa preencher ele de novo, igual na index. Caso de problema na validação, a página volta, e esse campo está vazio,ele não chega a entrar no método de redirecionar.
- Editado welington jrModerator sexta-feira, 18 de maio de 2018 00:18
-
-
testa ai
public ActionResult Create(PessoaView view) { //aqui ele vai preencher ele de novo ViewBag.CategList = new SelectList(db.Categs, "CategId", "Nome"); if (ModelState.IsValid) { db.Pessoas.Add(view.Pessoa); try { if (view.Foto != null) { var pic = Utilidades.UploadPhto(view.Foto); if (!string.IsNullOrEmpty(pic)) { view.Pessoa.Photo = string.Format("~/Content/Fotos/{0}", pic); } } db.SaveChanges(); return RedirectToAction("Index"); } catch (Exception ex) { ModelState.AddModelError(string.Empty, ex.Message); } } return View(view); }
- Marcado como Resposta GILBLAZER sexta-feira, 18 de maio de 2018 21:05
-