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);
}
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)
{
\\...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With