I'd like to dynamically change my ASP.NET form based on the user's input. First, the user have to select Item1 from a dropdown and based on the selected value, checkItem(); script will enable certain disabled-by-default input fields. I'd like to have something that would change the content of those input fields based on the selected value.
<tr>
<td style="text-align: center;">
item1:
</td>
<td colspan="2">
@Html.DropDownListFor(model => model.item1, (SelectList)ViewData["item1List"], htmlAttributes: new { onchange = "checkItem();", id = "Item1", name = "Item1", @class = "form-control", @style = "min-width: 100%!important;", @required = true })
</td>
</tr>
<tr>
<td style="text-align: center;">
item2:
</td>
<td colspan="2">
@if ( # I need something here, or have JavaScript instead #)
{
@Html.DropDownListFor(model => model.item2, (SelectList)ViewData["item2List"], htmlAttributes: new { id = "item2", name = "item2", disabled = false, @class = "form-control", @style = "min-width: 100%!important;" })
}
else
{
@Html.DropDownListFor(model => model.item2, (SelectList)ViewData["differentItem2List"], htmlAttributes: new { id = "item2", name = "item2", disabled = true, @class = "form-control", @style = "min-width: 100%!important;" })
}
</td>
</tr>
for example, if Item1 have 10 options: 5 locomotives and 5 motor trains, if the user selects a locomotive, the checkItem script will enable the item2 input field, that have a list of passenger cars, and if the user selects a motor train (for example a Stadler FLIRT) the item2 will have a list of other motor trains that compatible with the selected one (i.e: other Stadler motor trains).
How can I do something like this, without submitting the form or reloading the whole page?
CodePudding user response:
You can try to use ajax to get data from action:
$("#Item1").change(function () {
$.ajax({
url: "getList",
type: "GET",
data: {Item1: $("#Item1").val()},
success: function (data) {
var items = '';
$("#item2").empty();
$.each(data, function (i, item) {
items = "<option value='" item.value "'>" item.text "</option>";
});
$('#item2').html(items);
},
error: function (result) {
alert("error occured");
}
});
action:
public List<SelectListItem> getList(string Item1)
{
//return Item2 data here
}