views:

49

answers:

3

We are using asp.net mvc and having trouble in selecting the list of approved orders.

the orders are approved by selecting the checkbox against each order.

eg..

Order id Product Is Approved 1 book (depends if the user selects checkbox or not) 2 pen (depends if the user selects checkbox or not)

so currently we are doing something like this: and want to know if there a better way of implementating

View:

our false (as generated by microsoft)

on Post in Controller action method: we loop through the Orders (which is a list of Order object) in response(order id) = true,false: then we select that order or else we dont select

but u see we want to avoid writing that logic in controller.

so any ideas ?

A: 
public virtual ActionResult MyAction(FormCollection fVals)
{

    var q = from x in fVals.AllKeys
            where fVals[x] != "false"
            select x;
    var ids = q.ToList();


    // take id and call service with filter
    var result = this.myService.FilterResultByID(ids);


    // then return model
    return View(result);


}
gmcalab
A: 

Recently I answerer about similar problem:

http://stackoverflow.com/questions/2067786/asp-net-mvc-checkbox-group/2068216#2068216

You could do it like that (it will be propable foreach loop):

<% int i = 0; foreach(Order o in Model.Orders) { %>
    <%= Html.CheckBox("orders[" + i + "].Checked") %><%= Html.Hidden("orders[" + i "].ID",Order[i].ID) %><%= Html.Hidden("orders[" + i + "].Checked",false) %>
<% ++i; } %>

Your post method will be:

[HttpPost]
public ActionResult Test(OrdersSelection[] orders)
{
    var selectedOrders = orders.Where(o => o.Checked);
    return View();
}

public class OrdersSelection
{
     public bool Checked { get; set; }
     public bool ID { get; set; }
}
LukLed
A: 

You could do it in client script by appending/removing the order ids from a single hidden input as the user ticks/unticks. Use an array, push/splice as required and store in hidden field with join.
Then the controller would just have to read one response value to get the list of (comma-separated?) selected order ids.

AUSteve