如何从 ViewData MVC 中的列表中获取第二个相关值?

How to get second related value from List in ViewData MVC?

我有客户名单,其中包含所有详细信息,例如 客户 ID、名字、姓氏

GetAllCustomer() method code
      var customer = from d in dbContext.Customers
                                           select d;
                return customer.ToList();

在Index.cs 我已将名字绑定到下拉列表

var customerData =GetAllCustomer();

ViewBag.customerfirstname = new SelectList(customerData.Select(t=>t.firstname));

index.cshtml

@using (Html.BeginForm("Index", "Home", FormMethod.Get))
{
        <p>
            customer name : @Html.DropDownList("customerfirstname", "All")
            <input type="submit" value="Filter" /> 

        </p>
}

when I select any firstname from dropdown and click on submit I also want its customerId too.

我该怎么做?

您需要为 DropDownList 指定值字段和文本字段,现在它将 post CustomerID in for post against selected First Name :

var customerData =GetAllCustomer();

ViewBag.customerfirstname = new SelectList(customerData
                                           .Select(
                                                   t=>new 
                                                     { 
                                                      FirstName = t.firstname,
                                                     CustomerID = customerId),
                                          "CustomerID",
                                          "FirstName");

然后在您的视图中:

@Html.DropDownList("customerfirstname", "All")

在你的控制器中

ViewBag.customerfirstname  = new SelectList(customerData , "customerId", "firstname");

在您看来,编写此代码以绑定下拉列表。

@Html.DropDownList("getcustomerfirstname", ViewBag.customerfirstname as IEnumerable<SelectListItem>, "Select")