I'm fairly new to MVC. I have a dialog with multiple rows, each containing two dropdownlists. Row i contains a propertyOne dropdown list that sets the propertyOne property for field field id i. So in the onchange event I want to know that field id i in order to know from which field I should set propertyOne. The selection of PropertyOne affects the dropdown list items for PropertyTwo.
Does anyone know how I can do that?
Thank you in advance!
CorBins
Here's soms code (stripped down to the essentials). First the view:
<table id="propertiestable">
@foreach (PropertyField field in Model.Fields)
{
<tr>
<td>@Html.DisplayName(field.Id.ToString())</td>
<td>Property 1:</td>
<td>
@Html.DropDownListFor(m => m.PropertyOne, Model.ListItemsOne)
</td>
<td>Property 2:</td>
<td>
@Html.DropDownListFor(m => m.PropertyTwo, Model.ListItemsTwo)
</td>
<td>Property 3:</td>
<td>
@Html.TextBoxFor(m => m.PropertyThree)
</td>
<td>
<input class="btn btn-sm btn-danger" onclick="DeletePropClick(@field.Id)" value="X" name="[email protected]" />
</td>
</tr>
}
Model.Fields looks like this:
Public class PropertiesVM : EdgeActionBase {
public List<PropertyField> Fields { get; set; }
..
}
public class PropertyField {
public int Id { get; set: }
public string PropertyOne { get; set; }
public string PropertyTwo { get; set; }
public int PropertyThree { get; set; }
}
I'v tried something with JavaScript, but it don't work:
$('#@nameof(Model.Fields[i].PropertyOne)').on("change", function () {
alert('Hi there');
var selectedProperty = $(this).val();
var test = $(this).id();
var fields = '@Model.Fields';
let dataObj = { "Fields": fields, "PropertyOne": selectedProperty};
$.ajax({
url: "@Url.Action("SelectPropertyOnePartial")",
type: "POST",
data: JSON.stringify(dataObj),
contentType: "application/json",
success: function (data) {
if (data != null) {
$("#divProperties").html(data);
}
}
});
});
From your description of this question, I think you want to get the index of current row when you select an options for PropertyOne
property, So you can refer to this simple demo:
@for (int i = 0; i < Model.Fields.Count; i++)
{
<tr>
<td>@Html.DisplayName(Model.Fields[i].Id.ToString())</td>
<td>Property 1:</td>
<td>
@Html.DropDownListFor(x=>x.Fields[i].PropertyOne,Model.ListItemsOne, "---Select Employee---", new { Class = "ddlStyle", onchange = "Test(this)"} )
</td>
<td>Property 2:</td>
//..........
<br>
</tr>
}
<script>
function Test(data){
currentindex = data.name.substring(7, 8);
var Id = parseInt(currentindex) + 1;
alert("row index is :" + currentindex + "current row id is :" + Id)
}
</script>
Please note that the index of Fields start from 0, But the id of PropertyField
start from 1, So if you want to get id, You need to currentindex +1
.