Я пытаюсь создать новый продукт, но выдает ошибку
dropdown is not type of IEnumerable
я делаю тест - измените метод Post на Get, чтобы увидеть, пересекаются ли данные с URL-адресом или нет, и получают ли данные в порядке
Это контроллер:
public ActionResult Ajouter()
{
db = new IdentityDBEntities2();
ViewBag.categ = new SelectList(db.Categories, "Id", "libelle");
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
[Route("Create")]
public ActionResult Ajouter([Bind(Include = "Ida,description,image,Userid,Idc,titre")] Article article, HttpPostedFileBase postedFile)
{
try
{
if (ModelState.IsValid)
{
if (postedFile != null)
{
db = new IdentityDBEntities2();
article.image = Convert.ToString(postedFile.ContentLength);
postedFile.InputStream.Read(System.Text.Encoding.Unicode.GetBytes(article.image), 0, postedFile.ContentLength);
string fileName = System.IO.Path.GetFileName(postedFile.FileName);
string FilePath = "~/Content/img/" + fileName;
postedFile.SaveAs(Server.MapPath(FilePath));
article.UserId = System.Web.HttpContext.Current.User.Identity.GetUserId();
article.Idc = Convert.ToInt32(Request["Cab"]);
article.image = fileName;
db.Articles.Add(article);
ViewBag.categ = new SelectList(db.Categories, "Id", "libelle");
db.SaveChanges();
return RedirectToAction("Index");
}
}
else return View(article);
}
catch
{
return View();
}
return View();
}
- И это раскрывающийся список:
@Html.DropDownList("categ", null, "-- Select Category -- ", new { id = "subCategory" })
Я уже изменил содержимое раскрывающегося списка на
@Html.DropDownList("categ",(IEnumerable<SelectListItem>)ViewBag.Cab, "-- Select Category -- ", new { id = "subCategory" })
Но не работает. Благодарность





Вы назначаете ViewBag.categ тип List<Selectlistitem>, вы должны использовать Viewbag этого типа.
//first create List<selectlistitem>
List<SelectListItem> selectListItems = new List<SelectListItem>();
selectListItems.Add(new SelectListItem() { Value = "", Text = "Select" });
foreach (var item in db.Categories.ToList())
{
selectListItems.Add(new SelectListItem() { Value = item.Id.ToString(), Text = item.Name });
}
ViewBag.categ=selectListItems;
//use it in view
@Html.DropDownList("categ",(List<SelectListItem>)ViewBag.categ, "-- Select Category -- ", new { id = "subCategory" })
//с вашим кодом
public ActionResult Ajouter()
{
db = new IdentityDBEntities2();
List<SelectListItem> selectListItems = new List<SelectListItem>();
foreach (var item in db.Categories.ToList())
{
selectListItems.Add(new SelectListItem() { Value = item.Id, Text = item.libelle });
}
ViewBag.categ = selectListItems;
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
[Route("Create")]
public ActionResult Ajouter([Bind(Include = "Ida,description,image,Userid,Idc,titre")] Article article, HttpPostedFileBase postedFile)
{
try
{
if (ModelState.IsValid)
{
if (postedFile != null)
{
db = new IdentityDBEntities2();
article.image = Convert.ToString(postedFile.ContentLength);
postedFile.InputStream.Read(System.Text.Encoding.Unicode.GetBytes(article.image), 0, postedFile.ContentLength);
string fileName = System.IO.Path.GetFileName(postedFile.FileName);
string FilePath = "~/Content/img/" + fileName;
postedFile.SaveAs(Server.MapPath(FilePath));
article.UserId = System.Web.HttpContext.Current.User.Identity.GetUserId();
article.Idc = Convert.ToInt32(Request["Cab"]);
article.image = fileName;
db.Articles.Add(article);
List<SelectListItem> selectListItems = new List<SelectListItem>();
foreach (var item in db.Categories.ToList())
{
selectListItems.Add(new SelectListItem() { Value = item.Id, Text = item.libelle });
}
ViewBag.categ = selectListItems;
db.SaveChanges();
return RedirectToAction("Index");
}
}
else return View(article);
}
catch
{
return View();
}
return View();
}
// выпадающее содержимое
@Html.DropDownList("categ",(List<SelectListItem>)ViewBag.categ, "-- Select Category -- ", new { id = "subCategory" })
да бро брат
Вы создали List<SelectListItem> не SelectList
Да, брат, как ты сказал мне, я покажу тебе ошибку на картинке
Также используйте db.Categories как db.Categories.ToList()
где именно брат
Добавить метод расширения .ToList() в db.Categories
да, брат, я обновляюсь, скажи мне, что невозможно преобразовать список выбора, чтобы выбрать элемент списка для просмотра
хорошо спасибо брат
я написал ниже свой ответ
все та же ошибка списка и listitem, который я уже изменил, код, который вы мне даете, но не работает
Если хочешь, я могу подключить твой компьютер, чтобы проверить проблему
Хорошо, брат, спасибо, это мой фейсбук facebook.com/profile.php?id=100016967140017, сделай teamviewer или дай мне ссылку для удаленного управления машиной и реши эту проблему.
я написал тебе с лица
Не работает брат, потому что второй параметр принимает IEnumerable VALUE thnaks