I have an Index view in an MVC3 application with a @model which is ienumerable. In this model I have an accountID which I want to use to populate my dropdownlist in the view filter with the accounts so that the user will be able to filter for accounts.
Which is the best way to achieve this?
Thanks in advance.
This is the view:
@model IEnumerable<MoneyAdmin.Model.ContaAReceber>
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@Html.Partial("_SubmenuAdmin")
<div class="tituloCadastro">
Lista de Contas a Receber
</div>
<div class="buttonContainer novo">
@Html.ActionLink("Nova Conta", "Create")
</div>
<div class="filtros">
@using (Html.BeginForm()) {
<div class="filterField">
<label>Data Inicial:</label>
@Html.TextBox("dataInicial", @DateTime.Now.ToShortDateString())
</div>
<div class="filterField">
<label>Data Final:</label>
@Html.TextBox("dataFinal", @DateTime.Now.ToShortDateString())
</div>
<div class="filterField">
<label>Tipo de Conta:</label>
@Html.DropDownList("contaID")
</div>
<input type="submit" value="Atualizar" />
}
</div>
And the controller method:
public ViewResult Index(string dataInicial, string dataFinal, string contaID)
{
var crs = from cr in db.contasareceber.Include("contas")
select cr;
if (!string.IsNullOrEmpty(dataInicial) && !string.IsNullOrEmpty(dataFinal))
{
DateTime di = DateTime.Parse(dataInicial);
DateTime df = DateTime.Parse(dataFinal);
crs = crs.Where(cr => cr.dataPagamento >= di && cr.dataPagamento <= df);
}
return View(crs.ToList());
}
Thanks for everyone!
I found the answer as like this.
Populate the viewbag in the controller like that:
Then use it in the dropdownlist like that:
Simple and it works!
Thanks for everyone!