ASP.NET MVC:如何从分部视图向同控制器的其他视图传递选中值?
嘿,我来帮你梳理几种在ASP.NET MVC里把下拉框选中的@item.Time值传到同一控制器下另一个视图的实用方法,你可以根据自己的业务场景来选:
1. 表单同步提交(最基础的方式)
这是最直接的同步提交方案,把下拉框包裹在表单里,点击提交按钮后直接跳转到目标视图:
首先修改你的分部视图代码,给下拉框命名并包裹在表单中:
@model IEnumerable<ASP.Models.Staff> @using (Html.BeginForm("TargetViewAction", "YourControllerName", FormMethod.Get)) { <select name="selectedTime" class="form-control"> @foreach (var item in Model) { <option>@item.Time</option> } </select> <button type="submit" class="mt-2 btn btn-primary">确认传递</button> }
然后在你的控制器里,添加接收参数并返回目标视图的Action:
// 这里的YourControllerName替换成你的控制器实际名称 public ActionResult TargetViewAction(string selectedTime) { // 把选中的值存入ViewBag,方便目标视图读取 ViewBag.SelectedTime = selectedTime; // 或者更规范的做法是使用ViewModel传递 // var viewModel = new YourViewModel { SelectedTime = selectedTime }; // return View(viewModel); return View(); }
最后在目标视图里,就可以通过@ViewBag.SelectedTime(或者ViewModel的属性)拿到选中的时间值了。
2. AJAX异步传递(无刷新更新视图)
如果不想刷新整个页面,想用异步方式传递值并加载目标视图内容,可以用AJAX:
修改分部视图,给下拉框和按钮加ID,然后编写AJAX逻辑:
@model IEnumerable<ASP.Models.Staff> <select id="timeSelect" class="form-control"> @foreach (var item in Model) { <option>@item.Time</option> } </select> <button id="transferBtn" class="mt-2 btn btn-primary">异步传递</button> <!-- 用来加载目标视图的容器 --> <div id="targetViewContainer"></div> <script src="~/Scripts/jquery-3.6.0.min.js"></script> <script> $('#transferBtn').click(function() { var selectedTime = $('#timeSelect').val(); $.ajax({ url: '@Url.Action("TargetViewAction", "YourControllerName")', type: 'GET', data: { selectedTime: selectedTime }, success: function(response) { // 把返回的视图内容插入到容器中 $('#targetViewContainer').html(response); } }); }); </script>
控制器的TargetViewAction和第一种方法一样,接收参数后返回视图即可。
3. TempData传递(适合重定向场景)
如果需要先执行一些业务逻辑,再重定向到目标视图,就可以用TempData(它能跨请求保存数据):
首先在处理提交的Action里存储值:
public ActionResult SubmitSelectedTime(string selectedTime) { // 这里可以加入你的业务处理逻辑 // 把值存入TempData TempData["SelectedTime"] = selectedTime; // 重定向到目标视图的Action return RedirectToAction("TargetViewAction"); } public ActionResult TargetViewAction() { // 从TempData中取出值 var selectedTime = TempData["SelectedTime"] as string; // 如果需要后续请求还能读取,调用Keep方法 TempData.Keep("SelectedTime"); // 存入ViewBag传给视图 ViewBag.SelectedTime = selectedTime; return View(); }
对应的表单要指向SubmitSelectedTime这个Action,目标视图同样通过@ViewBag.SelectedTime获取值。
4. 路由参数跳转(直接通过URL传递)
如果想在用户选择下拉框选项时直接跳转,不用点击按钮,可以用onchange事件拼接URL参数:
@model IEnumerable<ASP.Models.Staff> <select onchange="location.href='@Url.Action("TargetViewAction", "YourControllerName")?selectedTime=' + this.value" class="form-control"> @foreach (var item in Model) { <option>@item.Time</option> } </select>
控制器的TargetViewAction还是接收selectedTime参数,然后传给目标视图即可。
内容的提问来源于stack exchange,提问作者Bơm Và Xe Tăng
相关产品推荐
相关产品推荐

