Reputation: 313
I have 2 dropdownlist where I want to get the dropdown value on change in my controller. If I select value from m.Cntry
then m.Yr
will be null and vice versa.
If any option is selected from first dropdown and then if any option is selected from second dropdown then I want the value of both string cntry,string yr
.
View
@Html.DropDownListFor(m => m.Cntry, new List<SelectListItem>
{
new SelectListItem {Value = "C1", Text = "Chile"},
new SelectListItem {Value = "F1", Text = "France" },
new SelectListItem {Value = "G1", Text = "Germany" },
},
new {@class = "form-control"})
@Html.DropDownListFor(m => m.Yr, new List<SelectListItem>
{
new SelectListItem {Value = N1, Text="New" },
new SelectListItem {Value = P1, Text = "Previous"},
new SelectListItem {Value = L1, Text = "Last" },
},
new { @class = "form-control"})
<div id="container"></div>
Controller
public ActionResult All(string cntry,string yr)
{
Details details = new Details();
var model = new ClsS();
if(cntry==null)
{
cntry = "C1";
}
else
{
yr = "N1";
}
var aa = details.Ra(cntry, yr);
return View(aa, model);
}
Script to get the change value from dropdown
$('#Cntry').change(function () {
var url = '@Url.Action("All")'
$('#container').load(url, { cntry: $('#Cntry').val() })
});
$('#Yr').change(function () {
var url = '@Url.Action("All")'
$('#container').load(url, { yr: $('#Yr').val() })
});
Upvotes: 1
Views: 545
Reputation:
You are only passing one value in each script. To pass the values of both selected options, you could would need to be
$('#container').load(url, { cntry: $('#Cntry').val(), yr: $('#Yr').val() })
You can also do this using just one script
var container = $('#container'); // cache it
$('#Cntry, #Yr').change(function () {
container.load(url, { cntry: $('#Cntry').val(), yr: $('#Yr').val() })
});
However, you are making unnecessary ajax calls (if a user wants to filter based on say "France" and "Last", then an ajax call is made as soon as "France" is chosen and it will display results for "New" when that is not what the user wants - an annoying user experience and a waste of resources). Instead have a separate 'Search' button, so the user can make their selections, and then get the results.
<button type="button" id="search">Search</button>
var container = $('#container');
$('#search').click(function () {
container.load(url, { cntry: $('#Cntry').val(), yr: $('#Yr').val() })
});
Upvotes: 1