我是 MVC 的新手。 我有一个包含多行的对话框,每行包含两个下拉列表。 第 i 行包含一个 propertyOne 下拉列表,它为字段字段 id i 设置 propertyOne 属性。 所以在 onchange 事件中我想知道那个字段 id i 以便知道我应该从哪个字段设置 propertyOne。 PropertyOne 的选择会影响 PropertyTwo 的下拉列表项。
有人知道我该怎么做吗?
提前谢谢你!
CorBins
这是 soms 代码(精简到最基本的部分)。 首先是观点:
<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 看起来像这样:
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; }
}
我已经用 JavaScript 尝试了一些东西,但它不起作用:
$('#@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);
}
}
});
});
根据你对这个问题的描述,我认为你希望在为
PropertyOne
属性选择选项时获取当前行的索引,所以你可以参考这个简单的演示:
@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>
请注意Fields的索引是从0开始的,但是
PropertyField
的id是从1开始的,所以如果你想得到id,你需要currentindex +1
.