0

I'm a beginner. I'm still studying. I have made this code, which works as intended. However, for each time I go back to another page, it can not, of course, save it to a list. It disappears directly after I'm gone from this page.

The server page looks like this

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult pizaCart(string pizaName, string pizaDesc, string pizaPrice)
    {

        List<pizaModel> cartList = new List<pizaModel>();
        toCart.CartList = cartList;

        pizaName = Request.Form["pizaName"];
        pizaDesc = Request.Form["pizaDesc"];
        pizaPrice = Request.Form["pizaPrice"];

        cartList.Add(new pizaModel { name = pizaName, desc = pizaDesc, price = pizaPrice });

        return View(toCart);

    }

html page looks like this.

    <form action="piza" method="post">

        <input class="n" type="text" name="pizaName" id="pizaName" value="" /><br />
        <input class="n" type="text" name="pizaDesc" id="pizaDesc" value="" /><br />
        <input class="n" type="text" name="pizaPrice" id="pizaPrice" value="" /><br />
        <button class="btn">add</button>

    </form>

"I have tried to google it and look for it lots of places, but havent found any good enough answer"

-- hmm i probably need a loop somewhere?

As you can see, it's a very simple way to post data to list. Is it possible that I can keep adding to my list? (Maybe it has something to do with lifecycle). Thank you very much for your time.

Hassaan
  • 3,931
  • 11
  • 34
  • 67
Bears
  • 41
  • 7
  • Are you persisting the data anywhere? What is `toCart.CartList` ? – Boney Nov 09 '18 at 19:14
  • Hallo sir, thank you for asking. I have forgotten to say, that it is a ViewModel object defiend as static in the class where ActionResult pizaCart resides. public class ViewModels { public List PizasList { get; set; } public List CartList { get; set; } } – Bears Nov 09 '18 at 19:18

2 Answers2

3

When you call

new List<pizaModel>()

...you are creating a new list. A new list has zero elements.

Immediately after that you call

cartList.Add(new pizaModel { name = pizaName, desc = pizaDesc, price = pizaPrice });

...which adds the current item to the list, which results in a list with one item.

There is no notion in this code of adding to an existing list, and it will never contain more than one item.

You will need to figure out some way of keeping the list from action to action. For example, you could persist the list in the browser and then post the whole list as JSON. Or you could store the list in a session variable or database table on the server side.

John Wu
  • 50,556
  • 8
  • 44
  • 80
0

You may use sessions as below

Session["myPizza"] = cartList ;

Then cast it from the end of your Action result as below

var SelectedList = (List<pizaModel>)Session["myPizza"];
PrathapG
  • 751
  • 1
  • 7
  • 21