分两步将复选框值从视图发送到控制器?

Ydh*_*hem 1 c# asp.net-mvc

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

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

  <input type="checkbox" name="tags[]" id="categorieTwo" value="2">
Run Code Online (Sandbox Code Playgroud)

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

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

*香草我的意思是它们不是用剃刀写的。

Dar*_*rov 5

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

<input type="checkbox" name="tags" id="categorieOne" value="1" />
<input type="checkbox" name="tags" id="categorieTwo" value="2" />
Run Code Online (Sandbox Code Playgroud)

进而:

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