Problem
So I had a chance to dabble in jQuery and html, which I haven’t used
in a minute but am familiar with. I came across the well documented challenge
of returning the selected value for an html dropdown list back to a C# class.
Dropdown list
data:
IList<SelectListItem>
StuffList { get; set;
}
...populate list then:
ViewBag.StuffSelection = StuffList;
html
table element:
<td>
<label for="StuffSelector" style="font-size:16px">Select Stuff:</label>
@Html.DropDownList("StuffSelection",
(IEnumerable<SelectListItem>)ViewBag.StuffSelection")
</td>
jquery function:
$(function () {
$('#StuffSelection').change(function
() {
document.location.href
= '@Url.Action("StuffSelectionClass",
"Home")' + '?SelectedStuff='
+ $(this).find(":selected").text();
});
back in
C#:
public ActionResult StuffSelectionClass
(string SelectedStuff)
{
String retrievedValue = SelectedStuff;
//then use the retrieved value for something or other
...
}
Solved
To give credit where it is due, this source
is where I found help. The solution was adding an id for the dropdown list thus:
html
table element:
<td>
<label for="StuffSelector" style="font-size:16px">Select Stuff:</label>
@Html.DropDownList("StuffSelection",
(IEnumerable<SelectListItem>)ViewBag.StuffSelection", new {@id="ddlStuffSelection"})
</td>
jquery function:
$(function () {
$('select#ddlStuffSelection').change(function
() {
document.location.href
= '@Url.Action("StuffSelectionClass",
"Home")' + '?SelectedStuff='
+ $(this).find(":selected").text();
});
Thank you source