Skip to main content
 首页 » 编程设计

c#之分两步将复选框值从 View 发送到 Controller

2024年02月13日12lonelyxmas

假设我在 Razor cshtml View 中有两个 vanilla* html 复选框。

  <input type="checkbox" name="tags[]" id="categorieOne" value="1"> 
 
  <input type="checkbox" name="tags[]" id="categorieTwo" value="2"> 

第一步是将这个 tags[] 数组发送到 Controller 。

第二步是在单独的变量中获取值 1 和 2(例如:为了显示“您选择了以下类别 1 ... 2”)

*我所说的 Vanilla 是指它们不是用 Razor 写的。

请您参考如下方法:

如果您将复选框从 tags[] 重命名为 tags,您的 Controller 操作可以将字符串数组作为参数来保存所选值:

<input type="checkbox" name="tags" id="categorieOne" value="1" /> 
<input type="checkbox" name="tags" id="categorieTwo" value="2" /> 

然后:

[HttpPost] 
public ActionResult SomeAction(string[] tags) 
{ 
    ... the tags array will contain the selected values (1, 2, ...) 
}