How to Display the Data Submitted by the User
by Editor GetCodeSnippet • January 5, 2016 • Microsoft .NET C# (C-Sharp), Microsoft ASP.NET MVC • 0 Comments
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;
1 2 3 4 5 6 7 8 9 10 11 12 13 |
[HttpPost] public ActionResult AddBook(Book newBook) { var collection = new List<Book>(); if (Session["collection"] != null) { collection.Add((Book) Session["collection"]); } collection.Add(newBook); Session["collection"] = collection; return RedirectToAction("Index"); } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
@model List<BooksCollection.Models.Book> @{ ViewBag.Title = "Home Page"; } <html> <head> <title>Book</title> </head> <body> <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) { <div class="col-sm-2"> Author : <br /> Title: <br /> Publisher : <br /> Publish Date: <br /> </div> <div class="col-sm-10"> @book.Authorname <br /> @book.Title <br /> @book.Publisher<br /> @book.PublishDate.ToShortDateString() </div> } </body> </html> |
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!