0
我有關於下拉的問題。從我的代碼中顯示數據庫的下拉值。但是,當我沒有填寫任何值,然後按輸入錯誤沒有ViewData項目類型'IEnumerable顯示。沒有類型爲「IEnumerable <SelectListItem」的ViewData項目
以下是我的代碼:
Category.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
namespace BusinessLayer
{
public interface ICategory
{
int CategoryId { get; set; }
string CategoryDescription { get; set; }
}
public class Category:ICategory
{
[Required]
public int CategoryId { get; set; }
[Required]
public string CategoryName { get; set; }
[Required]
public string CategoryDescription { get; set; }
[Required]
public SelectList CategoryList { get; set; }
}
}
CategoryBusinessLayer.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace BusinessLayer
{
public class CategoryBusinessLayer
{
public IEnumerable<Category> Categories
{
get
{
string connectionString =
ConfigurationManager.ConnectionStrings["DBCSS"].ConnectionString;
List<Category> categoryList = new List<Category>();
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("spGetAllCategory", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Category categories = new Category();
categories.CategoryId = Convert.ToInt32(rdr["CategoryId"]);
categories.CategoryName = rdr["CategoryName"].ToString();
categories.CategoryDescription = rdr["CategoryDescription"].ToString();
categoryList.Add(categories);
}
}
return categoryList;
}
}
}
ProductController.cs
[HttpGet]
[ActionName("Create")]
public ActionResult Create_Get()
{
Category category = new Category();
CategoryBusinessLayer cat = new CategoryBusinessLayer();
category.CategoryList = new SelectList(cat.Categories, "CategoryId", "CategoryName");
ViewBag.category = category.CategoryList;
return View();
}
Create.cshtml
@Html.DropDownList("CategoryId", (IEnumerable<SelectListItem>)ViewBag.category as SelectList, "Select Category")
謝謝。