Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select multiple data from table in view asp.net MVC4 Razor

i have following View where user has a table of products and i need select all data where "Quantity > 0" default is 0. But i dont know how can i get collection of data from table. Thanks for respond.

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
<fieldset>
    <legend>Produkty</legend>
    <table>
    @foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(model => item.Product.Name)
            </td>

            <td>
                @Html.DisplayFor(model => item.Product.Price)
            </td>
            <td>
                @Html.EditorFor(model => item.Quantity)
            </td>
        </tr>
    }
        <p>
            <input type="submit" value="Orders" />
        </p>

    </table>
</fieldset>
}

//Controller

 public ActionResult Index()
    {
        List<ProductListViewModel> productList = new List<ProductListViewModel>();

        foreach (var item in db.Products.ToList())
        {
            ProductListViewModel model = new ProductListViewModel();
            model.Product = item;
            model.Quantity = 0;
            productList.Add(model);
        }

        return View(productList);
    }
like image 893
Brandejs Avatar asked Oct 30 '25 18:10

Brandejs


1 Answers

Since you're using Html.EditorFor, things are easy. Put productList as parameter in your Index Action(for Post), MVC will auto combine form data to productList Object, so you just need to filter the quantity in server side with a loop. Of cause, to identify the product object, you'd better also add a hidden ID in your view.

<table>
@for(int i = 0; i<Model.Count; i++) {
    <tr>
        <td>
            @Html.HiddenFor(model => Model[i].Product.ID)
            @Html.DisplayFor(model => Model[i].Product.Name)
        </td>
        <td>
            @Html.EditorFor(model => Model[i].Quantity)
        </td>
    </tr>
}


[HttpPost]
public ActionResult Index(List<ProductListViewModel> productList)
    {
        \\...
    }
like image 172
Teddy Avatar answered Nov 01 '25 15:11

Teddy