Model Bind IList to selected elements only
I have an action method:
public ActionResult Delete(IList<Product> products)
And a table of products in my opinion. I have a model binding so that on submit I can populate the list products
. But I would like to fill it with only those products that are selected with a checkbox.
I think I can do it by changing the action method to this:
public ActionResult Delete(IList<Product> products, IList<int> toDelete)
And passing a list of checkboxes in toDelete
, but I'd really like to avoid changing the method signature if possible.
Is there a way to pass only selected items? Or will I have to write my own ModelBinder?
source to share
I don't understand why you don't want to change the signature, but if you don't, just go to ViewData ["toDelete"] or
int[] toDelete;
UpdateModel(toDelete, "toDelete");
or
public class FormViewModel {
IList<Product> Products {get;set;}
int[] ToDelete {get;set;}
}
var viewmodel = new FormViewModel();
UpdateModel(viewmodel, new[]{"Products", "ToDelete"});
source to share
You can always use a checkbox value to indicate whether an item should be removed or not.
The name of this value will refer to a property in your Product class.
<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>
Then when you get to your Delete () you can do something like:
products = products.Where(x=>x.ToDelete == false).ToList();
source to share