我正在开发一个单页网络应用程序。该页面有一个下拉列表。当一个项目被选中时,我使用 jQuery 将选定的值发布到一个操作方法,[现在,出于测试目的] 将该值添加到 ViewBag,并返回一个 PartialView。显然,我想将此部分视图放在同一页面中。因此,当我从下拉列表中选择一个值时,所选选项应显示在其下方。这是可能的还是我以错误的方式接近这个?
上下文的相关代码:
索引(主页)
<html>
@using SampleTracking.Models.ViewModels;
@model SamplingEventsVM
<head>
<title>@ViewBag.Title</title>
<script src="~/Scripts/jquery-2.1.1.js"></script>
<script type="text/javascript" src="~/Scripts/CustomScripts.js"></script>
</head>
<body>
<span id="SamplingEventDiv">
@Html.DropDownListFor(model => model.SelectedSamplingEvent, Model.SamplingEvents, new { @id = "SamplingEventSelection" })
</span>
<div id="SampleListDiv">
@{Html.RenderPartial("~/Views/Home/RetrieveSamples.cshtml");}
</div>
</body>
</html>
脚本
$(function (ready) {
$("#SamplingEventSelection").change(
function () {
$.post(
"/Home/RetrieveSamples",
{ selectedSamplingEvent: $("#SamplingEventSelection").val() },
function (data) {
$("#SamplingEventDetails").html(data)
}
)
}
)
});
动作方法脚本发布到
public ActionResult RetrieveSamples(string samplingEvent)
{
ViewBag.Selected = samplingEvent;
return PartialView();
}
局部视图
<div id="SamplingEventDetails" style="margin-top:100px;">@ViewBag.Selected</div>