문제

I am using MVC3. I'm binding the dropdown with the Data coming from a service. But after the page posts back and a filter applies to list, the dropdown shows the filter record value in the grid because I always bind the list coming from the service.

However, I want the dropdown to always show all the Records in the database.

도움이 되었습니까?

해결책

I don't understand your question that clearly. But it seems that it is a dropdown that you have on your view? I also have no idea what you are trying to bind so I created my own, but have a look at my code and modify it to fit in with your scenario.

In your view:

@model YourProject.ViewModels.YourViewModel

On the view there is a list of banks in a dropdown list.

Your banks dropdown:

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

Your view model that will be returned to the view:

public class YourViewModel
{
     // Partial class

     public int BankId { get; set; }
     public IEnumerable<Bank> Banks { get; set; }
}

Your create action method:

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

Your bank class:

public class Bank
{
     public int Id { get; set; }
     public string Name { get; set; }
     public bool IsActive { get; set; }
}

This is simple as it gets. I hope this helps :)

PS: Please remember with future posts, always give as much detail as possible so that we can help you better. Also don't forget to display code samples so that we can see what you have already done. The more details that we can have the better.

다른 팁

When you post the model back to the create[Http Post] action is it not possible to have the list of dropdown list values for the banks binded back to the model. I see that if the model is invalid, you call the code

viewModel.Banks = bankService.FindAll().Where(x => x.IsActive);

to get a list of all the banks again which I assume you need to hit the database again.

Thanks

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top