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

Razor页面点击提交按钮时如何获取选中的元素?

简洁实现Razor页面单选选项的后端值获取

方案思路

利用原生HTML单选按钮(<input type="radio">)的单选特性,结合样式自定义匹配现有UI需求,表单提交时自动携带选中值,后端直接通过绑定获取,无需额外维护隐藏输入框的状态。


步骤1:修改Razor视图的选项模板

给每个选项绑定单选按钮,通过隐藏原生radio样式保留原有UI风格:

<table class="table-fullWitdh" style="border-spacing: 13px">
    @{
        int counter = 0; 
        foreach (var elem in Model.ModelList)
        {
            if(counter % 7 == 0)
            {
                <tr>
                    @*每7个元素创建新行*@
                </tr>
            }
            <td>
                @*元素模板开始*@
                <label>
                    <input type="radio" name="SelectedCategoryId" value="@elem.CategoryId" style="display: none;" />
                    <table class="itemBackgrond centered">
                        <tr>
                            <td>
                                <p>@elem.Title</p>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <img class="imgSmall" src="@elem.ImageSource" />
                            </td>
                        </tr>
                    </table>
                </label>
                @*元素模板结束*@
            </td>
            counter++;
        }
    }
</table>
  • 用<label>包裹radio和选项表格,点击表格时自动选中对应radio
  • 所有radio设置相同name值,天然实现单选互斥
  • 隐藏原生radio显示,保留其表单提交功能

步骤2:简化jQuery事件处理

无需维护隐藏输入框的值,仅处理选中样式切换:

<script>
    // 点击选项切换选中样式
    $(".itemBackgrond").click(function () {
        $(".itemBackgrond").css("background-color", "#D8F1F0");
        $(this).css("background-color", "#c3e1ed");
        $('.baseButton').prop("disabled", false).css('opacity', '1');
    });

    // 页面加载时同步默认选中项的样式
    $(function() {
        const checkedRadio = $("input[name='SelectedCategoryId']:checked");
        if(checkedRadio.length > 0) {
            checkedRadio.closest("label").find(".itemBackgrond").css("background-color", "#c3e1ed");
            $('.baseButton').prop("disabled", false).css('opacity', '1');
        }
    });
</script>

步骤3:后端直接获取选中值

无需遍历FormCollection,通过参数绑定直接获取:

public async Task<IActionResult> OnPostButton_Submit(int selectedCategoryId)
{
    // selectedCategoryId即为选中项的CategoryId,直接使用
    return Page();
}

也可通过模型属性绑定:

public class YourPageModel : PageModel
{
    [BindProperty]
    public int SelectedCategoryId { get; set; }

    // 其他模型属性...

    public async Task<IActionResult> OnPostButton_Submit()
    {
        // 直接使用SelectedCategoryId属性
        return Page();
    }
}

方案优势

  • 依赖原生表单控件特性,避免自定义值同步逻辑的潜在bug
  • 代码更简洁,减少前后端冗余代码
  • 原生radio的互斥性天然保证单选逻辑,无需额外判断

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 18:47:12