我的列表应该根据下拉列表中所选的ID返回一个表。
控制器:
public List<tblResults> GetResult(int Id)
{
var v = (from a in entities.tblResults
where
a.result_id == Id
select a);
return v.ToList();
}
我认为这是目前的问题。
@if (ViewBag.Result != null)
{
@Html.DropDownListFor(m => m.maindropdown, new SelectList(ViewBag.ResultGroup, "id", "mainvalues"), "Please Select", new { @class = "form-control", @id = "dropdown" })
}
<div id="showorhide">
<table class="table table-striped" style="width:85%" align="center">
<tr>
@foreach (var item in ViewBag.GetResult)
{
<td>
@Html.DisplayFor(modelItem => item.result_id)
</td>
<td>
@Html.DisplayFor(modelItem => item.name)
</td>
</tr></table>
}
</div>
触发表的JS代码:
$("#dropdown").change(function () {
if ($(this).val() == "Please Select") {
$("#showorhide").hide();
}
else {
var selectedValue = this.value;
$.get('@Url.Action("GetResult", "Home")', { id: selectedValue }, function (result) {
if (result) {
$("#showorhide").html(result);
}
});
}
您将ajax请求发送到GetProduct
,但您的操作是GetResult
,因此您将数据发送到了错误的位置。我稍微整理一下你的代码。由于ViewBag.GetResult
为空,并且您试图将json结果附加为html,因此您的数据不会到来。因此,您需要获取结果,并将每个结果项作为表元素追加。并确保您的GetResult
返回一些值。
控制器:
public JsonResult GetResult(int Id)
{
var v = (from a in entities.tblResults
where
a.result_id == Id
select a);
return Json(v, JsonRequestBehavior.AllowGet);
}
视图:
@if (ViewBag.Result != null)
{
@Html.DropDownListFor(m => m.maindropdown, new SelectList(ViewBag.ResultGroup, "id", "mainvalues"), "Please Select", new{ @class = "form-control", @id = "dropdown" })
}
<div id="showorhide">
<table class="table table-striped" style="width:85%" align="center" id="resultTable">
@foreach (var item in ViewBag.GetResult)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.result_id)
</td>
<td>
@Html.DisplayFor(modelItem => item.name)
</td>
</tr>
}
</table>
</div>
js:
$("#dropdown").change(function () {
if ($(this).val() == "Please Select") {
$("#showorhide").hide();
}
else {
var selectedValue = this.value;
$.get('@Url.Action("GetResult", "Home")', { id: selectedValue }, function (result) {
if (result) {
for (let index = 0; index < result.length; index++) {
const e = result[index];
$("#resultTable").append("<tr><td>" + e.result_id + "</td><td>" + e.name + "</td></tr>");
}
}
});
}
});