Reputation: 33
After many years of getting a lot of great advice here, I finally have hit a wall teaching myself MVC4 ASP.net.
I used this post this post to pass a List of Type Class from my controller, to my view, and back to the controller..
public ActionResult SelectProducts()
{
displayProductsList = db.Products.ToList();
displayProductsList.ForEach(delegate(Product p)
{
//get list of recievables for the product
GetReceivablesByProductId(p.ProductID).ForEach(delegate(Receivable r)
{
//Get count of items in inventory for each recievable
p.CurrentInventory += this.CountItemsByReceivableID(r.RecievableID);
});
});
return View(FilterProductInventoryList(displayProductsList));
}
And here is my view code..
@model List<CarePac2.Models.Product>
@{
ViewBag.Title = "SelectProducts";
}
<h2>SelectProducts</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<table>
@*row values*@
@for (int i = 0; i < Model.Count; i++)
{
<tr>
<td>@Html.DisplayFor(m => m[i].Brand)</td>
<td>@Html.DisplayFor(m => m[i].ProductName)</td>
<td>@Html.DisplayFor(m => m[i].UnitType)</td>
<td>@Html.DisplayFor(m => m[i].SalePrice)</td>
<td>@Html.DisplayFor(m => m[i].CurrentInventory)</td>
<td>
@Html.EditorFor(m => m[i].OrderQuantity)
@Html.ValidationMessageFor(m => m[i].OrderQuantity)
</td>
<td></td>
</tr>
}
</table>
<p>
<input type="submit" value="Save" />
@*<input type="submit" value="Cancel" />*@
</p>
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
Here the view show it has values for the List that was passed from controller to view..
Visually the view displays the data correctly (apparently i can't post an image of it until i have 10 reputation to post images)
when i hit submit and return to the controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SelectProducts(List<Product> selectedProducts)
{
if (ModelState.IsValid)
{
}
}
The variable selectedProducts Is NOT NULL. The list has 3 Product items in it, however, as you can see in the image below in the debugger, even though i have 3 product items, none of the values exist from when the List of Product was originally passed to the view...
for example (since i can't post images yet):
selectedProducts[0].ProductID=0
selectedProducts[0].ProductName=null
selectedProducts[1].ProductID=0
selectedProducts[1].ProductName=null
Upvotes: 3
Views: 1819
Reputation: 11330
You need to use @Html.HiddenFor()
:
@Html.HiddenFor(m => m[i].ProductID)
@Html.HiddenFor(m => m[i].ProductName)
This will send the data back to the controller. This creates an <input type="hidden">
that will be part of the form POST.
Upvotes: 6