私はドロップダウンに関する問題があります。私のコードから、データベースからのドロップダウン値が表示されます。しかし、私は任意の値を記入しないと、 'IEnumerable表示のViewData項目がないというエラーを入力してください。続き'IEnumerable <SelectListItem>タイプのViewDataアイテムがありません
は私のコードです:
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
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
[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")
ありがとうございました。