【问题标题】:How to set Dropdownlist selected value in mvc3如何在 mvc3 中设置下拉列表选定值
【发布时间】:2013-06-19 15:02:40
【问题描述】:

我有一个与 TempData 绑定的下拉列表。当它第一次出现时它显示所有值。选择一个特定值后,该值正确保存在数据库中。但所选值没有显示。我给下面是我的代码。

为了检索我已经写在索引动作控制器中

TempData["Clients"] = (IEnumerable<SelectListItem>)ClientService.GetALLClientsName().Select(C=>new SelectListItem { Value=C.CLIENT_ID.ToString(),Text=C.CLIENT_NAME});

编辑后检索时无法获取所选值。我在下面这样用剃刀写了

@if (TempData["SelectedClientName"] != null && TempData["SelectedClientId"] != null)
                       {
                           foreach (SelectListItem sli in lstClients)
                           {
                               if (sli.Value.Equals(TempData["SelectedClientId"].ToString()))
                               {
                                   sli.Text = TempData["SelectedClientName"].ToString();
                                   sli.Value = TempData["SelectedClientId"].ToString();
                                   sli.Selected = true;
                                   break;    

                               }
                           }

                       }

                      @Html.DropDownList("drpClientName", lstClients, "--Select--")

我已经在 lstClients 中转换了 TempData["Clients"]。请帮助我。

【问题讨论】:

  • 您不应将下拉数据保存在 TempData 中。改用 ViewBag 或 ViewData

标签: asp.net-mvc-3


【解决方案1】:

您应该使用 DropDownListFor 并且 ViewModel 包含 ClientId 字段:

你的视图模型:

public class YourViewModel{
    public int ClientId {get;set;}
}

查看:

@Html.DropDownListFor( x => x.ClientId, new SelectList( Clients.GetClientsList(Model.ClientId), "Value", "Text", Model.ClientId))

在Clients.cs中(如):

public static List<SelectListItem> GetClientsList(int client)
{
    var dataContext = new YourDataContext(  );
    var data = dataContext.GetModelsFn(client).ToList();

    var result = ( from res in data
               select new SelectListItem()
                          {
                              Text = res.ClientName,
                              Value = res.ClientId.ToString(),
                              Selected = res.ClientId == client
                          } ).ToList();

    return result;
}

【讨论】:

  • 我不能使用下拉列表。
【解决方案2】:
public ActionResult Index(){
    var selectedClientId = 5; // for example (change it with your variable)
    ViewBag.Clients = new SelectList(ClientService.GetALLClientsName(), 
                              "CLIENT_ID", "CLIENT_NAME", selectedClientId)
}

查看:

@Html.DropDownList("drpClientName", (SelectList)ViewBag.Clients, "--Select--")

TempData 有不同的用法。它的行为类似于Session,但它只能在下一个请求中存活。它在重定向和想要传递数据时很有用。请参阅this link 以更好地了解其中的区别。

【讨论】:

  • @amitabha 我不知道他在控制器中的代码,这是如何正确操作的示例。他会将我的硬编码值更改为他自己的变量值。我写了“例如”评论来说明这一点:)
【解决方案3】:

你可以在 controller.ie 的模型中设置它当你创建 TempData["Clients"]

将您想要的 selectlistitem 设置为选中状态。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-09
    相关资源
    最近更新 更多