0

我是 mvc 4 的新手,但正在取得进展。我对如何在视图模型的选择列表中选择一个项目感到疯狂。这是我的控制器代码;

ViewBag.DepartmanListesi = new SelectList(VeriTabani.UnvanDepartmanlaris, "UDepId", "Departman");

在我的视图模型中,我列出了一个不同的数据库,但在这个列表中,一个字段包含一个 .UnvanDepartmanlaris而不是显示 id 的 id,我想显示 id 的名称。但我尝试过的没有奏效。你能帮我么。

我搜索了很多东西,但其中大部分是关于如何设置下拉列表的。我找不到我的问题的任何答案。

先感谢您。我将等待任何回应

4

2 回答 2

3

试试这个,

控制器

 public List<CustomerModel> GetCustomerName()
        {
            // Customer DropDown
            using (dataDataContext _context = new dataDataContext())
            {
                return (from c in _context.Customers
                        select new CustomerModel
                        {
                            CustomerId = c.CID,
                            customerName = c.CustomerName
                        }).ToList<CustomerModel>();
            }
        }

  [HttpGet]
        public ActionResult CustomerInfo()
        {

            var List = GetCustomerName();
            ViewBag.CustomerNameID = new SelectList(List, "CustomerId", "customerName");
            return View();
        }

看法

@Html.DropDownList("CustomerId", (SelectList)ViewBag.CustomerNameID, "--Select--")

模型

public class CustomerModel
    {
        public int CustomerId { get; set; }

        public string customerName { get; set; }

        public List<SelectListItem> customerNameList { get; set; }
}
于 2013-09-02T09:19:14.510 回答
0

我正在使用以下方法。希望能帮助到你:

创建助手类(我在这里有我所有的选择列表)

Public static class Helper
{
public static List<SelectListItem> GetList()
        {
            var result = new List<SelectListItem>();
            var ctx = new YourContext();

            var items = from n in ctx.Clients
                        select new SelectListItem
                        {
                            Text = n.Client.Name,
                            Value = n.ClientID.ToString()
                        };

            foreach (var item in items)
                result.Add(item);
            return result;
        }
}

比在您看来:

@Html.DropDownList("GetClients", Helper.GetList())

为我工作。

于 2013-09-02T08:15:20.337 回答