使用数组将多个参数(无线电)从视图传递到控制器

时间:2017-06-05 11:24:11

标签: c# asp.net-mvc razor asp.net-mvc-5

我想在不使用模型的情况下发布55到100个项目,这些项目可能是虚假或真实的,从视图到我的控制器。这是我在Razor View中的代码:

@using(Html.BeginForm("User","User",FormMethod.Post,new{enctype="multipart/form-data"}))
    {

        <input type="radio" name="answer1">Choice one</input>
        <input type="radio" name="answer1">Choice two</input>
        <input type="radio" name="answer2">Choice three</input>
        <input type="radio" name="answer2">Choice four</input>

    ....

    <input type="radio" name="answer55">Choice fifty five</input>
    <input type="radio" name="answer55">Choice fifty six</input>

    <button type="submit">Send</button>
                                   }

控制器:

[HttpPost]
public async Task<ActionResult> User(Array....)
{
return view();}

如何使用阵列将所有参数(单选按钮)发送到控制器。我感谢您的所有解决方案。

3 个答案:

答案 0 :(得分:0)

也许创建一个包含size bool元素数组的视图模型类,然后将每个元素绑定到Razor页面中的单选按钮。

public class BooleanViewModel
{
   public BooleanViewModel(int size)
   {
      BoolArray = new bool [size];
   }

   public bool [] BoolArray {get; set;} 
}

设置您的Razor页面模型:@model BooleanViewModel

然后,在Razor中你可以使用@Html.RadioButtonFor(model => model.BoolArray[0], "textForButton")等。 您还可以进行一些foreach循环并浏览model.BoolArray中的所有项目。

答案 1 :(得分:0)

试试吧: 在你的控制器中:

 // GET: Home
        public ActionResult Index()
        {
            List<MyItem> radioItems = new List<MyItem>();
            radioItems.Add(new MyItem() { Caption="radio1", Value="radio1Value"});
            radioItems.Add(new MyItem() { Caption="radio2", Value="radio2Value"});
            radioItems.Add(new MyItem() { Caption="radio3", Value="radio3Value"});
            radioItems.Add(new MyItem() { Caption="radioN", Value="radioNValue"});
            return View(radioItems);
        }
        [HttpPost]
        public void IndexPost(List<string> items)
        {
            // todointo item has your selected item
            var x = items;

        }

在你的cshtml中:

@using (Html.BeginForm("IndexPost", "Home", FormMethod.Post))
        {
            foreach (var item in Model)
            {

                <input type="checkbox" name="items" value="@item.Value">@item.Caption
            }

            <button Type="submit">Send</button>

        }

答案 2 :(得分:0)

在视图中:要使阵列正常工作,请按照以下格式命名单选按钮,以便模型绑定工作

@using (Html.BeginForm("Index", "Home")) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary()
    <input type="radio" name="param[0]" value="one" >
    <input type="radio" name="param[0]" value="two" >
    <input type="radio" name="param[1]" value="three" >
    <input type="radio" name="param[1]" value="four" >
    <input type="radio" name="param[2]" value="five" >
    <input type="radio" name="param[2]" value="six" >
  <input type="submit" value="submit" />
}

在Post ActionMethod中:

 [HttpPost]       
 public ActionResult Index(string[] param)
                { //
    }

然后您将在action方法中获取param数组中的值。 你可以拥有任意数量的单选按钮。 ModelBinder将负责绑定。

相关问题