I have a very strange problem with my Dropdown. When I upload submit this error appears:
There is no ViewData item of type 'IEnumerable' that has the key 'Diocese'.
But I think the error is not in this Dropdown because I always did this and it always worked.
Controller:
public ActionResult CriarCatequese()
{
//Lista de Dioceses para escolher uma vigararia
ViewBag.Dioceses = new SelectList(db.Diocese, "DioceseID", "Nome");
return View();
}
View:
<div class="form-group">
@Html.Label("Diocese", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-3">
@Html.DropDownList("Diocese", (SelectList)ViewBag.Dioceses, "--Escolha uma diocese--", htmlAttributes: new { @class = "form-control" })
</div>
</div>
I think the problem may be here, that I have to select several parishes in the ListBox, the ListBox is populated with an AJAX call, I did this with the following code:
view:
<div class="form-group">
@Html.Label("Paroquias", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-3">
@Html.ListBoxFor(m => m.SelectedParoquias, new MultiSelectList(string.Empty, "ParoquiaID", "Nome"), htmlAttributes: new { @class = "form-control" })
</div>
</div>
ModelView:
public class CatequeseViewModel
{
public IEnumerable<int> SelectedParoquias { get; set; }
//selecionar Paroquias
public Catequese Catequese { get; set; }
public IEnumerable<SelectListItem> TodasParoquias { get; set; }
private List<int> _selecionarParoquias;
public List<int> SelecionarParoquias
{
get
{
if (_selecionarParoquias == null)
{
_selecionarParoquias = Catequese.Paroquias.Select(m => m.ParoquiaID).ToList();
}
return _selecionarParoquias;
}
set { _selecionarParoquias = value; }
}
}
Controller:
public ActionResult CriarCatequese(CatequeseViewModel m)
{
if (ModelState.IsValid)
{
var catequese = new Catequese
{
NomeCatequese = m.Catequese.NomeCatequese,
Morada = m.Catequese.Morada,
Localidade = m.Catequese.Localidade,
CodigoPostal = m.Catequese.CodigoPostal,
Telefone = m.Catequese.Telefone,
email = m.Catequese.email
};
//codigo para adicionar as paroquias
catequese.Paroquias = db.Paroquia.Where(p => m.SelectedParoquias.Contains(p.ParoquiaID)).ToList();
db.Catequese.Add(catequese);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(m);
}