Suppose we have an online book store and an online customer wants to purchase a book. Now there should be a link in our web page like “Add Book in Cart”. After click on this link, customer should have a form to fill the book’s details.
When the user click on ‘Submit’ button, the HTML submitted back to the server and addBook() method having HttpPost attribute is called which will have key-pair list of book’s properties and values. This is model binding, it is going to get the stream of data from the client to the server and will create new object called ”newBook” and from this object we are creating a new list. As shown in code below;
public ActionResult AddBook(Book newBook)
var collection = new List<Book>();
if (Session["collection"] != null)
Session["collection"] = collection;
Here we use session variable that are used to store and retrieve the values for the user. In the above code, we are checking if there is a book inside the session . Then we are adding the current book in the collection and updating the session. Then we are going to redirect it to the Index View as. shown in the code above.
Now lets see the code of Index View.
ViewBag.Title = "Home Page";
<h3>Purchase a book</h3>
<div><b>@Html.ActionLink("Add Book in Cart", "AddBook")</b></div>
<div><h4>The Detail of Book you want to Purchase</h4></div>
@foreach (var book in Model)
Author : <br />
Title: <br />
Publisher : <br />
Publish Date: <br />
@book.Authorname <br />
@book.Title <br />
The customer enters the book’s detail in the form and submit it. Session variable stores that value and redirect it to Index View and Index view will display the data submitted by the user. Output is shown below;
Best WordPress Themes and Plugins with Great Team and Support!