【问题标题】:How to collect multiple checkbox values using FormCollection?如何使用 FormCollection 收集多个复选框值?
【发布时间】:2012-04-27 06:16:46
【问题描述】:

基于 Darin 对我的问题的回答 Ho to display multiple checkbox selection based on user's selection from dropdown? 我正在根据下拉选择显示多个复选框。

现在,一旦用户在我的页面上发布表单(带有多个输入),我就会使用 FormCollection 收集所有数据。我遇到的问题是如何从 formcollection 中提取那些选定的复选框值?复选框的数量将根据下拉菜单中的不同选择而改变,因此我认为请求每个复选框值将不起作用。

谁能帮我解决这个问题。

流程如下图:

模型中的属性

public class Subcategory
{
    public string Name { get; set; }
    public int ID { get; set; }
    public bool Flag { get; set; }
}

在存在其他表单输入的实际视图中显示 PartialView:

 <div id="checkboxlist">
      @if (Model.SubCategories != null)
      {
           @Html.Partial("SubCategories", Model.SubCategories)
      }
 </div>    

PartialView SubCategories.cshtml

@model IEnumerable<MyProject.Entities.Subcategory>
@{
// we change the HTML field prefix so that input elements
// such as checkboxes have correct names in order to be able
// to POST the values back 
ViewData.TemplateInfo.HtmlFieldPrefix = "checkboxlist";
}
<span>subcategory</span>
<div id="subcategories" style="margin-left: 130px;margin-top: -20px;" data-role="fieldcontain">
   <fieldset data-role="controlgroup">
      @Html.EditorForModel()
   </fieldset>
</div> 

EditorTemplates Subcategory.cshtml

@model MyProject.Entities.Subcategory
<div class="editor-label">
   @Html.CheckBoxFor(c => c.Flag, new { type = "checkbox" })
   <label for="@Model.ID">@Model.Name</label>
   @Html.HiddenFor(c => c.Flag)
   @Html.HiddenFor(c => c.ID)
   @Html.HiddenFor(c => c.Name)
</div>

jquery 根据下拉选择显示复选框:

 $('#Category').change(function () {
    var subcategoriesUrl = $(this).data('subcategoriesurl');
    var categoryId = $(this).val();
    $('#checkboxlist').load(subcategoriesUrl, { category: categoryId });
 });

【问题讨论】:

    标签: c# asp.net-mvc asp.net-mvc-3 c#-4.0


    【解决方案1】:

    不要使用FormCollection。那是弱类型。使用视图模型。像这样:

    [HttpPost]
    public ActionResult Foo(MyViewModel model)
    {
        // model.BusinessSubCategories should contain a list of Subcategory
        // where for each element you could use the Flag property to see if
        // it was selected or not
        ...
    }
    

    还请注意,您在部分中使用的字段前缀之间存在不一致:

    ViewData.TemplateInfo.HtmlFieldPrefix = "checkboxlist";
    

    和视图模型集合属性:Model.BusinessSubCategories。因此,如果您希望默认模型绑定器能够在您回发时填充此属性,请确保修复前缀以使用正确的属性名称。

    【讨论】:

    • 有没有办法使用 FormCollection?我改用 FormCollection 来实现验证码。
    • 是的,有,但要准备好编写可怕的代码,例如:var flag1 = fc["BusinessSubCategories[0].Flag"]。也就是说:永远不要那样做。永远不要使用 FormCollection。我看不出与验证码有什么关系。如果您需要一些其他信息,请在视图模型上添加一个具有正确名称的属性,然后让您的控制器操作采用此视图模型并忘记 FormCollection。
    猜你喜欢
    • 1970-01-01
    • 2015-05-13
    • 2021-11-10
    • 2010-12-15
    • 2011-02-06
    • 2013-11-22
    • 1970-01-01
    • 2016-04-25
    相关资源
    最近更新 更多