I currently have a foreach
loop in my MVC view that creates a table row for each each with a drop down list that need to execute a JavaScript during the onchange
event. This onchange
event will populate another drop down list within the same table row based on the selected value.
var count = 0;
@foreach(var item in Model.Items)
{
<tr>
<td>
@Html.DropDownListFor(
model => item.SelectedId,
new SelectList(item.MyList, "ID", "Name"),
new
{
@class = "form-control",
@id = string.Concat("MyControl", count),
@name = string.Concat("MyControl", count),
@onchange = string.Format("javascript:MyJsFunction(this.value, {0});", count);"
}
)
@Html.DropDownListFor(
model => item.ChildSelectedId,
new SelectList(item.MyChildList, "ID", "Name"),
new
{
@class = "form-control",
@id = string.Concat("MyChildControl", count),
@name = string.Concat("MyChildControl", count)
}
)
</td>
</tr>
count++;
}
At the bottom of the view, I have the following <script>
block:
<script>
$(document).ready(function () {
//do some other stuff here
});
function MyJsFunction(value, id) {
var loadingMsg = "<option value='0'>Loading...</option>";
var url = "/MyApp/Controller/Action/";
var targetControl = "#MyChildControl" + id
$(targetControl).html(loadingMsg).show();
$.ajax({
url: url,
data: { Id: value },
cache: false,
type: "POST",
success: function (data) {
var markup = "<option value='0'>- My Child Control - </option>";
for(var i = 0; i < data.length, i++) {
markup += "<option value=" + data[i].Value + ">" + data[i].Text + "</option>";
}
$(targetControl).html(markup).show();
},
error: function (response) {
alert("error: " + response);
}
});
}
</script>
When I run my code and change the value in the drop down list, I get the following error:
Uncaught ReferenceError: MyJsFunction is not defined
How do I resolve this error?