I have a page with 2 dropdownlist. one country, one currency and depend on country I want to fill currency dropdownlist and after click button I want to fill the grid from database. I simplfied my code to show what I have tried. What is the best and easist approach?
public ActionResult ddlCountry()
{
var countryList = new List<string>();
countryList.Add("US");
countryList.Add("GB");
return View(countryList);
}
public ActionResult ddlCurrency(string country)
{
var curencyList = new List<string>();
if(country == "US")
curencyList.Add("USD");
if(country == "GB")
curencyList.Add("GBP");
return View(curencyList);
}
public ActionResult Index(string country, string currency)
{
var viewModels = new List<FooViewModel>();
//code gets values from database
return View(viewModels);
}
<div>
@using (Html.BeginForm())
{
<table>
<tr>
<td>Country</td>
<td>@Html.DropDownListFor(model => model.SelectedId, new SelectList(Model.Choices, "Id", "Text"), "Choose... ")</td>
<td>Currency</td>
<td>@Html.DropDownListFor(model => model.SelectedId, new SelectList(Model.Choices, "Id", "Text"), "Choose... ")</td>
</tr>
</table>
@Html.ActionLink("Search", "Index", new {})
}
</div>
@using (Html.BeginForm("Search", "Index", new { Country = "IN", Currency = "INR" }, FormMethod.Post, new { id = "foo" }))
{
<div>
@Html.Grid(Model).Named("valueGrid").Columns(columns =>
{
columns.Add(vm => vm.Country).Titled("Country");
columns.Add(vm => vm.Currency).Titled("Currency");
columns.Add(vm => vm.Value).Titled("Value");
}).WithPaging(25).Sortable(true).Filterable(true)
</div>
}
Since the question spans multiple requirements I will try to break it down.
In your
ViewModel
you want to create Lists ofSelectViewItem
for your DDLs:Remember to fill
_countries
with your data in your constructor.In your View:
Repeat this process for the other DDL and create another property for the Grid data.
You basically need to do the cascading dropdown loading approach. To start, first load the Country dropdown on your page load. For that, in the GET action of your page, send a list of SelectListItem's to the view so that we can use to build the SELECT element options
Now make sure your view is strongly typed to a list of
SelectListItem
. In your view, you can use the Html.DropDownList helper method to render the dropdownNow you need to listen to the change event of the first dropdown, get the value and make an ajax call to get the options for your second dropdown.
Now make sure you have your GetCurrencies action method which accepts the country and return a List of SelectListItem in JSON format
Now after selecting dropdown values, when you submit the form, the selected options will be available in the parameters of your Index action.