绑定 DropdownList 并在回发后维护

New*_*ing 1 dropdownbox asp.net-mvc-3

我正在使用 MVC3。我将下拉列表与来自服务的数据绑定在一起。但是在页面回发并且过滤器应用于列表之后,下拉列表会在网格中显示过滤器记录值,因为我总是绑定来自服务的列表。

但是,我希望下拉菜单始终显示数据库中的所有记录。

Bre*_*ogt 5

我不是很清楚你的问题。但它似乎是您认为的下拉列表?我也不知道您要绑定什么,所以我创建了自己的,但请查看我的代码并修改它以适应您的场景。

在您看来:

@model YourProject.ViewModels.YourViewModel
Run Code Online (Sandbox Code Playgroud)

在视图中有一个下拉列表中的银行列表。

您的银行下拉列表:

<td><b>Bank:</b></td>
<td>
     @Html.DropDownListFor(
          x => x.BankId,
          new SelectList(Model.Banks, "Id", "Name", Model.BankId),
          "-- Select --"
     )
     @Html.ValidationMessageFor(x => x.BankId)
</td>
Run Code Online (Sandbox Code Playgroud)

您将返回到视图的视图模型:

public class YourViewModel
{
     // Partial class

     public int BankId { get; set; }
     public IEnumerable<Bank> Banks { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

您的创建操作方法:

public ActionResult Create()
{
     YourViewModel viewModel = new YourViewModel
     {
          // Get all the banks from the database
          Banks = bankService.FindAll().Where(x => x.IsActive)
     }

     // Return the view model to the view
     // Always use a view model for your data
     return View(viewModel);
}

[HttpPost]
public ActionResult Create(YourViewModel viewModel)
{
     if (!ModelState.IsValid)
     {
          // If there is an error, rebind the dropdown.
          // The item that was selected will still be there.
          viewModel.Banks = bankService.FindAll().Where(x => x.IsActive);

          return View(viewModel);
     }

     // If you browse the values of viewModel you will see that BankId will have the
     // value (unique identifier of bank) already set.  Now that you have this value
     // you can do with it whatever you like.
}
Run Code Online (Sandbox Code Playgroud)

您的银行类:

public class Bank
{
     public int Id { get; set; }
     public string Name { get; set; }
     public bool IsActive { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

这很简单。我希望这有帮助 :)

PS:请记住以后的帖子,总是提供尽可能多的细节,以便我们可以更好地帮助您。另外不要忘记显示代码示例,以便我们可以看到您已经完成的操作。我们可以拥有的细节越多越好。