I have this script in my view (this is the source):
<script type="text/javascript" src="../../Scripts/jquery-1.7.1.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#state").prop("disabled", true);
$("#country").change(function () {
if ($("#country").val() != "Please select") {
var options = {};
options.url = "/companies/getbolag";
options.type = "POST";
options.data = JSON.stringify({ country: $("#country").val() });
options.dataType = "json";
options.contentType = "application/json";
options.success = function (states) {
$("#state").empty();
for (var i = 0; i < states.length; i++) {
$("#state").append("<option>" + states[i] + "</option>");
}
$("#state").prop("disabled", false);
};
options.error = function () { alert("Fel vid bolagshämtning!"); };
$.ajax(options);
}
else {
$("#state").empty();
$("#state").prop("disabled", true);
}
});
});
</script>
It populates a second dropdown list based on what is selected in the first. Cascading dropdowns.
This HtmlHelper triggers the script but when submitted omits the value:
@Html.DropDownList("country", ViewData["kundLista"] as SelectList)
This one does the opposite, it submits the value but does not trigger the script:
@Html.DropDownListFor(model => model.Kund, ViewData["kundLista"] as SelectList)
I need it to both trigger the script and submit the value. How do I do this?
Since the name of your property is Kund
, second helper creates a select element which has both id
and name
fields set to Kund
. On the other hand your script uses id country
to address this select. So you have two options:
Change id used in the script to #Kund
:
$("#Kund").change(function () {
if ($("#Kund").val() != "Please select") {
Use first helper with correct name and id:
@Html.DropDownList("Kund", ViewData["kundLista"] as SelectList), new {@id="country"})