4

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);
    }

1 Answer 1

3

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)
    {
        \\...
    }
Sign up to request clarification or add additional context in comments.

1 Comment

@Brandejs I've updated the answer, changing foreach to for and it works. This method is to generate a name for inputs like '[0].Quantity' and '[1].Quantity', then MVC will combine them into a list

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.