【问题标题】:Get Checkbox values to controller获取复选框值到控制器
【发布时间】:2013-05-17 18:11:39
【问题描述】:

在下面的视图中,我试图将选中的复选框值发送到控制器以保存在数据库中。

<div class="editor-label">
                <%: Html.LabelFor(model => model.Addresses) %>
            </div>

             <div class="editor-field">
             <% foreach (var item in Model.Addresses)
                { %>
       <input type="checkbox" 
         id="<%: item.addressID %>"
         name="addressOption"
         value="<%: item.addressID%>"/>
       <label for="optionId"><%: item.address%></label>
       <br />
         <% } %>
               </div>
               <br />
            <div class="editor-label">
                <%: Html.LabelFor(model => model.Mobile) %>
            </div>

控制器:

AdvanceClient cli = new AdvanceClient();

                    if (ModelState.IsValid)
                    {

                        cli.Mobile = Request.Form["Mobile"];

                        foreach (var item in Request.Form["Addresses"])
                        {
                            //here i need to get the checked checkbox values
                        }
                    }

我一直在获取选中复选框的值

【问题讨论】:

    标签: asp.net asp.net-mvc asp.net-mvc-2


    【解决方案1】:

    您可以从以下位置获取逗号分隔字符串中的所有值:

    var selectedValues = Request.Form["mySharedName"];
     // This is now a comma separated list of values that was checked
    

    对你来说它将是:Request.Form["addressOption"]

    然后使用for 循环,您可以获得所有值

    【讨论】:

    • 你好。感谢您的解决方案。现在我已将逗号分隔的字符串保存到数据库中。你能告诉我如何在编辑视图中检查相关值吗?
    【解决方案2】:

    你可以像这样存储数组

    <input type="checkbox" name="addressOption[0]" id="..." value="..." />
    <input type="checkbox" name="addressOption[1]" id="..." value="..." />
    <input type="checkbox" name="addressOption[2]" id="..." value="..." />
    

    现在你只需要在你的模型中有一个同名的数组

    List<int> addressOption;
    

    它会在提交时自动填充。

    【讨论】:

      猜你喜欢
      • 2012-08-06
      • 2020-05-29
      • 2013-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多