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

如何通过Model将提交按钮的布尔值从View传递到Controller

解决方法

你的问题出在按钮的asp-for用法不正确,asp-for并不适合直接用在提交按钮上。要实现点击不同按钮提交对应布尔值到Model的Response字段,只需给按钮指定正确的name属性(对应Model里的字段名),并设置对应的value即可:

修改后的视图代码

@model Model
@using (Html.BeginForm("MyAction", "Controller", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <button type="submit" class="btn btn-outline-success btn-rounded" name="Response" value="true">Approved</button>
    <button type="submit" class="btn btn-outline-danger btn-rounded" name="Response" value="false">Reject</button>
}

控制器代码无需修改

public ActionResult MyAction(Model model)
{
    // model.Response会自动绑定为点击按钮对应的true/false
    // 后续处理逻辑
}

原理说明

当点击提交按钮时,表单会将该按钮的name和value作为表单数据提交。因为我们把按钮的name设为Response(和Model里的字段名一致),ASP.NET MVC会自动将提交的"true"/"false"字符串转换为布尔类型,绑定到model.Response上。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 22:10:43