【发布时间】:2021-03-05 02:46:18
【问题描述】:
我需要有关使用 jQuery 在 ASP.NET Core razor 视图页面中创建动态控件的帮助。
jQquery用于获取动态控件选择值:
@section scripts {
<script>
$(function () {
$("button[type='submit']").click(function () {
event.preventDefault();
var properties = [];
$("#tb_properties tr:first").find("td").each(function (index, item) {
var propertyname = $(item).find("input[type='text']").val();
var selctedvalue = $(item).find("select").val();
properties.push('"' + propertyname + '":"' + selctedvalue + '"');
});
var jsonstr = '{' + properties.join(",") + '}';
//var jsobject = JSON.parse(jsonstr);
$.ajax({
type: "Post",
url: "/KEMap/Insert",
//data: jsobject,
data: jsonstr,
contentType:"application/json",
success: function (response) {
toastr.info(response.status + "<br>" + "<br>" + response.message);
$("#tb_properties select").val("");
$("#partial_div").load(window.location.href + " #partial_div");
},
error: function (xhr, textStatus, errorThrown) {
console.log('in error');
}
});
});
});
</script>
}
这个 jQuery 在下表结构中运行良好
<table class="table" id="tb_properties" style="width:100%">
<tr>
@foreach (var itemApiProp in ViewBag.ApiProp)
{
<td>
<input type="text" value="@itemApiProp.Key" class="form-control" readonly="readonly" />
<select class="form-control">
<option value="">--Select-- </option>
@foreach (var itemK360Prop in ViewBag.K360Prop)
{
<option>@itemK360Prop.Key</option>
}
</select>
</td>
}
</tr>
</table>
但是当我尝试像下面这样更改表结构时,我的 jQuery 不再正常工作,即使我正在获取表的第一行 td 控制值。有人可以帮帮我吗?
<table class="table" id="tb_properties" style="width:100%">
@foreach (var itemApiProp in ViewBag.ApiProp)
{
<tr>
<td>
<input type="text" value="@itemApiProp.Key" class="form-control" readonly="readonly" />
</td>
<td>
<select class="form-control">
<option value="">--Select-- </option>
@foreach (var itemK360Prop in ViewBag.K360Prop)
{
<option>@itemK360Prop.Key</option>
}
</select>
</td>
</tr>
}
</table>
【问题讨论】: