You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在ASP.NET Core MVC(C#)中如何通过按钮将单选框值传递到另一个网页

ASP.NET Core MVC 单选按钮值跨页传递实现方案

以下是三种常用的实现方式,可根据业务场景选择:

方案1:原生表单提交(无JS依赖,最推荐)

直接通过表单提交将单选值传递到目标页对应接口:

  • 源页面定义表单,单选按钮组设置统一的name属性,提交按钮指定type="submit"即可
<!-- 源页面.cshtml -->
<form asp-action="TargetAction" asp-controller="Home" method="get">
    <div>
        <input type="radio" name="selectedValue" value="option1" id="opt1" />
        <label for="opt1">选项1</label>
    </div>
    <div>
        <input type="radio" name="selectedValue" value="option2" id="opt2" />
        <label for="opt2">选项2</label>
    </div>
    <div>
        <input type="radio" name="selectedValue" value="option3" id="opt3" />
        <label for="opt3">选项3</label>
    </div>
    <button type="submit">提交跳转到目标页</button>
</form>
  • 后端接口直接接收参数,传递到目标视图
// HomeController.cs
public IActionResult TargetAction(string selectedValue)
{
    // 处理选中值后传入目标页
    ViewBag.SelectedValue = selectedValue;
    return View();
}

如果不想让值暴露在URL中,把表单的method改成post即可,后端接收逻辑不变。

方案2:JS动态拼接跳转地址(适合需要前端预校验的场景)

如果跳转前需要前端先做校验逻辑,可以通过JS获取选中值后拼接跳转:

<!-- 源页面.cshtml -->
<div>
    <input type="radio" name="selectedValue" value="option1" id="opt1" />
    <label for="opt1">选项1</label>
</div>
<div>
    <input type="radio" name="selectedValue" value="option2" id="opt2" />
    <label for="opt2">选项2</label>
</div>
<button id="jumpBtn">跳转到目标页</button>

<script>
document.getElementById('jumpBtn').addEventListener('click', function(){
    // 获取选中的单选值
    const checkedVal = document.querySelector('input[name="selectedValue"]:checked')?.value;
    if(!checkedVal){
        alert('请先选择一个选项');
        return;
    }
    // 拼接地址跳转
    window.location.href = `/Home/TargetAction?selectedValue=${encodeURIComponent(checkedVal)}`;
})
</script>

后端接收逻辑和方案1完全一致。

方案3:TempData存值(适合敏感值不暴露URL的场景)

如果既不想用post表单,也不想让值出现在地址栏,可以通过TempData中转传递:

  • 源页面表单提交到中转接口
<form asp-action="TransferAction" asp-controller="Home" method="post">
    <!-- 单选按钮结构和前面一致 -->
    <button type="submit">提交跳转</button>
</form>
  • 后端中转存储后重定向
[HttpPost]
public IActionResult TransferAction(string selectedValue)
{
    TempData["SelectedVal"] = selectedValue;
    return RedirectToAction("TargetAction");
}

public IActionResult TargetAction()
{
    var val = TempData["SelectedVal"] as string;
    ViewBag.SelectedValue = val;
    return View();
}

TempData基于Session实现,仅单次跳转有效,目标页刷新后值会自动失效,适合单次传递的场景。

内容的提问来源于stack exchange,提问作者Computer Questions

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 07:54:06