Quindi il mio codice funzionava prima. Non so cosa ho fatto perché ciò accadesse e non riesco a risolverlo. Ho visto persone dire di resettare il ModelState. (ModelState.Clear();) Ma questo non ha aiutato. Inoltre, non aiuta che io sia ancora abbastanza nuovo per MVC. Qualsiasi aiuto sarebbe apprezzato. Grazie.L'elemento ViewData con la chiave 'CategoryId' è di tipo 'System.Int32', ma deve essere di tipo 'IEnumerable <SelectListItem>'?
Controller:
public ActionResult Create()
{
ActiveDirectoryModel adm = new ActiveDirectoryModel();
ViewBag.notifyto = adm.FetchContacts();
var model = Populate();
return View(model);
}
[HttpPost]
public ActionResult Create(CreateViewModel model)
{
if (ModelState.IsValid)
{
model.leaf.Date = DateTime.Now.Date;
model.leaf.Category = model.CategoryId;
model.leaf.SubCategory = model.SubCategoryId;
model.leaf.AssignedTo = model.AssignedToId;
model.leaf.CoAssignedTo = model.CoAssignedToId;
model.leaf.Status = model.StatusId;
model.leaf.Priority = model.PriorityId;
//model.lead.Parent = model.ParentID;
db.LeafItems.AddObject(model.leaf);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(model);
}
public CreateViewModel Populate()
{
ActiveDirectoryModel adm = new ActiveDirectoryModel();
var model = new CreateViewModel
{
AssignedToItems = adm.FetchContacts(),
CoAssignedToItems = adm.FetchContacts(),
NotifyToItems = adm.FetchContacts(),
CategoryItems =
from c in new IntraEntities().CategoryItems.ToList()
select new SelectListItem
{
Text = c.Name,
Value = c.ID.ToString()
},
SubCategoryItems =
from sc in new IntraEntities().SubCategoryItems.ToList()
select new SelectListItem
{
Text = sc.Name,
Value = sc.ID.ToString()
},
StatusItems =
from s in new IntraEntities().StatusItems.ToList()
where s.IsPriority == false
select new SelectListItem
{
Text = s.Name,
Value = s.ID.ToString()
},
PriorityItems =
from p in new IntraEntities().StatusItems.ToList()
where p.IsPriority == true
select new SelectListItem
{
Text = p.Name,
Value = p.ID.ToString()
}
};
return model;
}
Vista:
<div class="createTopInner">
<div class="editor-label">
@Html.LabelFor(model => model.leaf.Category)
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.CategoryId, Model.CategoryItems, "")
@Html.ValidationMessageFor(model => model.leaf.Category)
</div>
</div>
Modello:
public int CategoryId { get; set; }
public IEnumerable<SelectListItem> CategoryItems { get; set; }
Ho risolto il problema eseguendo il mio metodo populate se ModelState.IsValid = false. Una volta passate 8 ore, posso postare questa come una vera risposta. Non voglio che nessuno sprechi il loro tempo fino ad allora. – Ber53rker