如何在视图页面中显示名称字段而不是id字段

时间:2017-02-28 19:13:57

标签: asp.net-mvc-4

我正在尝试在我的视图页面中显示CategoryName,但它只显示我从下拉列表中插入的CategoryId。你能看看我的代码并帮助我吗?我需要做什么来显示CategoryName而不是CategoryId ??

提前谢谢。

以下是我的代码:

ProductController.cs

 public ActionResult Index()
        {
            ProductBusinessLayer productBusinessLayer = new ProductBusinessLayer();
            List<Product> products = productBusinessLayer.Products.ToList();
            return View(products);
        }

ProductBusinessLayer.cs

 public IEnumerable<Product> Products
        {
            get
            {
                string connectionString =
                    ConfigurationManager.ConnectionStrings["DBCSS"].ConnectionString;

                List<Product> productList = new List<Product>();

                using (SqlConnection con = new SqlConnection(connectionString))
                {
                    SqlCommand cmd = new SqlCommand("spGetAllProducts", con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    con.Open();
                    SqlDataReader rdr = cmd.ExecuteReader();
                    while (rdr.Read())
                    {
                        Product products = new Product();
                        products.ProductID = Convert.ToInt32(rdr["ProductID"]);
                        products.CategoryId = rdr["CategoryId"].ToString();

                        productList.Add(products);
                    }
                }

                return productList;
            }
        }

Product.cs

 public class Product
    {
        public int ProductID { get; set; }
        public string CategoryId { get; set; }

    }

Index.cshtml

 @Html.DisplayFor(modelItem => item.CategoryId)

Category.cs

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();                                             categoryList.Add(categories);
                    }
                }

                return categoryList;
            }
        }

0 个答案:

没有答案