-1

I have a Strongly typed view of Type IEnumerable<MVC.Models.Product>. I am receiving null values when i iterate through the IEnumerable in the controller.

View

    @model IEnumerable<MVC.Models.Product>
   <h2>Product</h2>
    @foreach (var item in Model)
    {

      using (Html.BeginForm("AddToCart", "Home"))
        {
               @Html.DisplayFor(modelItem => item.ProductID)
            <div>
                @Html.DisplayFor(modelItem => item.ProductName)
            </div>
            <div>
                @Html.DisplayFor(modelItem => item.ProductVendor)
            </div>
            <div>
                @Html.DisplayFor(modelItem => item.ProductDesc)
            </div>
            <div>
                @Html.DisplayFor(modelItem => item.productPrice)
            </div>
            <div>
                @Html.TextBox("Quant")
            </div>
            <div>
                <button type="submit" value="Add to cart">Add to cart</button>
            </div>
        }

    }

Controller

     public ActionResult Index(int? page)
    {
        using (AutoPartsSystemEntities3 db = new Models.AutoPartsSystemEntities3())
        {
            var Query = db.Products;
            int pageSize = 3;
            int pageNumber = (page ?? 1);
            return View(Query.OrderBy(e => e.ProductName).ToPagedList(pageNumber,pageSize));
        }

    }

    public ActionResult Product(int id)
    {
        using (AutoPartsSystemEntities3 db = new AutoPartsSystemEntities3())
        {
            var Query = (from p in db.Products
                        where p.ProductID == id
                        select p).ToList();

            return View(Query);
        }
    }
    [HttpPost]
    public ActionResult AddToCart(IEnumerable<Product> p, int Quant)
    {
        double TotalPrice = 0;
        int ProductID = 0;
        foreach (Product pro in p)
        {
            TotalPrice = pro.productPrice * Quant;
            ProductID = pro.ProductID;
        }
        using (AutoPartsSystemEntities8 db = new AutoPartsSystemEntities8())
        {
            db.Carts.Add(new Cart { ProductId = ProductID, CheckOut = false, DateCreated = DateTime.Now, Price = (float)TotalPrice, Quantity = Quant, UserId = 1 });
            db.SaveChanges();

        }
        return RedirectToAction("Index", "Home");
    }

Product Class

public partial class Product
{
    public int ProductID { get; set; }
    public string ProductName { get; set; }
    public string ProductVendor { get; set; }
    public string ProductDesc { get; set; }
    public double productPrice { get; set; }
}
aj12
  • 288
  • 3
  • 17
  • do you get the null in the GET action or in the POST (the function you posted)? In your view you are creating many forms.. – Roelant M Sep 19 '16 at 18:13
  • @KirkWoll I have added index controller – aj12 Sep 19 '16 at 18:17
  • @RoelantM in the POST action – aj12 Sep 19 '16 at 19:05
  • You creating a form for each item in your collection which makes so sense (you can only submit one form at a time. And your `foreach` loop is generating `name` attributes that have no relationship to your model (your also generating duplicate `id` attributes which is invalid html). Use one form and add a property for the quantity to your model then refer [this answer](http://stackoverflow.com/questions/30094047/html-table-to-ado-net-datatable/30094943#30094943) –  Sep 19 '16 at 21:58
  • @StephenMuecke I have made those changes but it still dint help – aj12 Sep 19 '16 at 22:29
  • What changes? Your code makes no sense. You need one form and inside that for a `for` loop of `EditorTemplate` as per the link in the previous comment. And your POST method needs to be `public ActionResult AddToCart(List model)` –  Sep 19 '16 at 22:31
  • And I have just rolled back your edit. You cannot completely change your question (the other answers and comments would make no sense). And you need to generate form controls if you want to post back values (`DisplayFor()` does not generate an input) –  Sep 19 '16 at 22:34
  • @StephenMuecke I don't want the result in a textbox, I want it just to be displayed in the screen. When the button is clicked, The Quantity and object is sent to the controller – aj12 Sep 19 '16 at 22:37
  • You cannot send your model to the controller if you do not create inputs for each property of your model! (use hidden inputs if necessary). But in any case you should only be submitting the ID of the product and the quantity –  Sep 19 '16 at 22:39
  • @JagajagaBagabaga - You've made a few statements, shown some code, but you haven't asked us a question. – Enigmativity Sep 20 '16 at 00:23

1 Answers1

0

Each form is sending back a single MVC.Models.Product, not a Collection (IEnumerable). Try:

[HttpPost]
public ActionResult AddToCart(Product p, int Quant)

And modfiy the controller to refect the fact that you're only saving one product at a time.

and add:

@Html.HiddenFor(modelItem => item.ProductID) 

under the displayFor for it so it posts back.

Chad McGrath
  • 1,561
  • 1
  • 11
  • 17