【问题标题】:How to get second related value from List in ViewData MVC?如何从 ViewData MVC 中的列表中获取第二个相关值?
【发布时间】:2015-05-13 06:29:33
【问题描述】:

我有客户列表,其中包含所有详细信息,例如 客户 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>
}

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

我该怎么做?

【问题讨论】:

  • A &lt;select&gt; 只回发 1 个值(或多个值的数组),因此您应该使用基于 ID 属性的值字段和基于文本字段的值创建 SelectList在 Name 属性上(并绑定到 ID 属性)
  • 首先你的表单方法应该是 Post,而不是 Get。然后在 BeginForm 中,您应该将操作的名称放在负责处理表单帖子的 Home 控制器中。该操作应具有合适的模型作为输入参数,该模型将代表您的表单数据。
  • @MladenOršolić,OP 的代码中没有任何内容表明它必须是 FormMethod.Post。提交按钮的文本“过滤器”表明它实际上应该是一个 GET
  • 此链接提供了在 mvc c-sharpcorner.com/UploadFile/4d9083/… 中创建下拉菜单的示例

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


【解决方案1】:

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

var customerData =GetAllCustomer();

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

然后在你的视图中:

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

【讨论】:

  • @Html.DropDownList("customerfirstname", "All"),此代码会将控制器中的数据绑定到下拉列表吗?因为您传递的是字符串而不是 SelectList
  • 是的,它将被视为 viewbag 键
  • @AmitKumar,第二个参数用于labelOption - 它在&lt;select&gt; 元素中添加&lt;option value=""&gt;All&lt;/option&gt; 作为第一个选项
  • @Anand 写 @Html.DropDownList("customerfirstname") 表示用 IEnumerable&lt;SelectListItem&gt; 填充下拉列表,它位于 ViewBag.customerfirstname 中,如果它没有找到带有键的 ViewBag 则什么也不会发生,否则如果找到它就会填充
  • @Ehsan,谢谢你的解释
【解决方案2】:

在你的控制器中

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

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

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

【讨论】:

  • 什么时候点击提交按钮如何获取两个值?关于索引操作结果方法?
  • 这两个值是什么意思?
  • 您将只获得选定的 CustomerId。在您的帖子操作中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-21
  • 1970-01-01
  • 2020-04-06
  • 2020-04-08
  • 1970-01-01
相关资源
最近更新 更多