我有一个动作方法设定:

public ActionResult Delete(IList<Product> products)

和的产品在我的视图的表。我有模型绑定工作,以便在提交我可以填充products列表。但我想仅与该经由复选框所选的产品来填充它。

我想我可以通过改变操作方法本做到这一点:

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

和路过的复选框列表中toDelete,但我真的想避免可能的话改变方法签名。

有一种方法,以通过仅所选项目吗?还是我将不得不编写自定义的模型绑定器?

有帮助吗?

解决方案

我不明白你为什么不想更改签名,但如果你真的不,刚刚接触计算机[“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"});

其他提示

您总是可以使用复选框值指示是否删除的项目或没有。

该值的名称将涉及您的产品类的属性。

<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>

然后,当您到达删除(),你可以这样做:

products = products.Where(x=>x.ToDelete == false).ToList();
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top