Bind Checkboxes to int array/enumerable in MVC

后端 未结 3 1616
慢半拍i
慢半拍i 2021-02-05 08:46
@Html.CheckBox(\"orderNumbers\", new { value = 1 })
@Html.CheckBox(\"orderNumbers\", new { value = 2 })
@Html.CheckBox(\"orderNumbers\", new { value = 3 })
@Html.CheckBo         


        
相关标签:
3条回答
  • 2021-02-05 09:02

    Because thats how the provided CheckBoxFor helper is working.

    You have to generate the html for the checkboxes yourself. Then the hidden inputs are not generated and you will get only the selected integer values.

    0 讨论(0)
  • 2021-02-05 09:03

    In addition to alok_dida's great answer. Since all the values are integers, you can have your controller code take an array of integers and avoid doing the conversion yourself.

    This works in MVC4+:

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Index(int[] orderNumbers)
    {
        return View();
    }
    
    0 讨论(0)
  • 2021-02-05 09:14

    You can get all the checked values by the following way.

    Controller code :

        public ActionResult Index()
        {            
            return View();
        }
    
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Index(string[] orderNumbers)
        {
            return View();
        }
    

    View Code :

    @using (Html.BeginForm())
    {
        <input name="orderNumbers" type="checkbox" value="1" />
        <input name="orderNumbers" type="checkbox" value="2" />
        <input name="orderNumbers" type="checkbox" value="3" />
        <input name="orderNumbers" type="checkbox" value="4" />
        <input name="orderNumbers" type="checkbox" value="5" />
    
        <input type="submit" name="temp" value="hi" />
    }
    

    Please keep one thing in my mind that, you need to give same name to all checkboxes. In array you will get values for all checked checkboxes.

    0 讨论(0)
提交回复
热议问题