代码之家  ›  专栏  ›  技术社区  ›  jeef3

仅绑定选定项的IList的模型

  •  2
  • jeef3  · 技术社区  · 16 年前

    我有一个动作方法设置:

    public ActionResult Delete(IList<Product> products)
    

    在我看来还有一个产品目录。我已经进行了模型绑定工作,以便在提交时填充 products 名单。但我只想用通过复选框选择的产品填充它。

    我想我可以通过将动作方法改为:

    public ActionResult Delete(IList<Product> products, IList<int> toDelete)
    

    并将复选框列表传递给 toDelete 但如果可能的话,我真的希望避免更改方法签名。

    是否有方法仅传递所选项目?或者我需要编写一个自定义的ModelBinder?

    2 回复  |  直到 16 年前
        1
  •  1
  •   queen3    16 年前

    我不明白你为什么不想更改签名,但如果你真的不想,只需访问viewdata[“todelete”]或

    int[] toDelete;
    UpdateModel(toDelete, "toDelete");
    

    public class FormViewModel { 
       IList<Product> Products {get;set;}
       int[] ToDelete {get;set;} 
    }
    
    var viewmodel = new FormViewModel();
    UpdateModel(viewmodel, new[]{"Products", "ToDelete"});
    
        2
  •  2
  •   Dan Atkinson    16 年前

    您可以始终使用复选框值来指示是否删除该项。

    该值的名称将与产品类中的属性相关。

    <form>
        <% for(int i = 0; i < products.Count) { %>
          <div>
            <input type="hidden" name='<%=string.Format("products[{0}].Property1", i) %>' value='<%= products[i].Property1 %>' />
            <input type="hidden" name='<%=string.Format("products[{0}].Property2", i) %>' value='<%= products[i].Property2 %>' />
            <input type="hidden" name='<%=string.Format("products[{0}].Property3", i) %>' value='<%= products[i].Property3 %>' />
            <input type="checkbox" name='<%=string.Format("products[{0}].ToDelete", i) %>' value='true' />
          </div>
        <% } %>
    </form>
    

    然后,当您进入delete()时,您可以执行如下操作:

    products = products.Where(x=>x.ToDelete == false).ToList();