Vì vậy, mã của tôi đã hoạt động trước đó. Tôi không biết những gì tôi đã làm cho điều này xảy ra và tôi dường như không thể sửa chữa nó. Tôi đã thấy mọi người nói để thiết lập lại ModelState. (ModelState.Clear();) Nhưng điều đó không giúp được gì. Ngoài ra, nó không giúp tôi vẫn còn khá mới mẻ với MVC. Bất kỳ trợ giúp sẽ được đánh giá cao. Cảm ơn.Mục ViewData có khóa 'CategoryId' thuộc loại 'System.Int32' nhưng phải thuộc loại 'IEnumerable <SelectListItem>'?
Bộ điều khiển:
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;
}
Xem:
<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>
mẫu:
public int CategoryId { get; set; }
public IEnumerable<SelectListItem> CategoryItems { get; set; }
Tôi đã khắc phục sự cố bằng cách chạy phương thức điền của tôi nếu ModelState.IsValid = false. Sau 8 giờ, tôi có thể đăng bài này dưới dạng câu trả lời thực sự. Tôi chỉ không muốn bất cứ ai lãng phí thời gian của họ cho đến lúc đó. – Ber53rker