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

时间:2015-05-13 06:29:34

标签: c# asp.net-mvc asp.net-mvc-4 viewstate viewbag

我有客户列表,其中包含所有详细信息 客户ID,名字,姓氏

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

在Index.cs中 我将firstname绑定到下拉列表

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>
}
  

当我从下拉列表中选择任何名字并单击提交时    我也想要它的customerId。

我怎么能这样做?

2 个答案:

答案 0 :(得分:3)

你需要为DropDownList指定值字段和文本字段,现在它将发布CustomerID以针对所选的名字发布帖子:

var customerData =GetAllCustomer();

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

然后在你的视图中:

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

答案 1 :(得分:1)

在您的控制器中

IIndicesOperationResponse result = null;
                    if (!objElasticClient.IndexExists(elastic_indexname).Exists)
                    {
                        result = objElasticClient.CreateIndex(elastic_indexname, c => c.AddMapping<dynamic>(m => m.Type("_default_").DynamicTemplates(t => t
                                                    .Add(f => f.Name("string_fields").Match("*").MatchMappingType("string").Mapping(ma => ma
                                                        .String(s => s.Index(FieldIndexOption.NotAnalyzed)))))));
                }

在您的视图中,将此代码编写为bind dropdown。

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